package com.epalmpay.service.yunstream.impl;



import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.epalmpay.bean.FlowChargeOrderBean;
import com.epalmpay.bean.OilcardChargeOrderBean;
import com.epalmpay.bean.OilcardRechargeInfoBean;
import com.epalmpay.status.Rescode;
import com.epalmpay.config.Global;
import com.epalmpay.dto.datareport.BaseReportInDTO;
import com.epalmpay.dto.datareport.FlowChargeReportInfoListOutDTO;
import com.epalmpay.dto.datareport.FlowChargeReportListOutDTO;
import com.epalmpay.dto.datareport.OilChargeReportInfoListOutDTO;
import com.epalmpay.dto.datareport.OilChargeReportListOutDTO;
import com.epalmpay.dto.system.BaseOutDTO;
import com.epalmpay.dto.yunliu.oilcard.BaseOilOrderInDTO;
import com.epalmpay.dto.yunliu.oilcard.CancelOilChargeInDTO;
import com.epalmpay.dto.yunliu.oilcard.CreateOilOrderInDTO;
import com.epalmpay.dto.yunliu.oilcard.FlowOrderListInDTO;
import com.epalmpay.dto.yunliu.oilcard.OilCardOrderReChargeInDTO;
import com.epalmpay.dto.yunliu.oilcard.OilcardChargeListInDTO;
import com.epalmpay.entity.Group;
import com.epalmpay.entity.GroupPayconfig;
import com.epalmpay.entity.Member;
import com.epalmpay.entity.MemberCard;
import com.epalmpay.entity.Page;
import com.epalmpay.entity.StatisFlowCharge;
import com.epalmpay.entity.StatisOilCharge;
import com.epalmpay.entity.TradeOffline;
import com.epalmpay.entity.YsFlowChargeOrder;
import com.epalmpay.entity.YsOilcard;
import com.epalmpay.entity.YsOilcardMember;
import com.epalmpay.entity.YsOilcardOrder;
import com.epalmpay.entity.YsOilcardRechargeInfo;
import com.epalmpay.entity.YsOilcardRepOrder;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.BizEnum.PaymentType;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.GroupMapper;
import com.epalmpay.mapper.GroupPayconfigMapper;
import com.epalmpay.mapper.MemberCardMapper;
import com.epalmpay.mapper.MemberMapper;
import com.epalmpay.mapper.StatisFlowChargeMapper;
import com.epalmpay.mapper.StatisOilChargeMapper;
import com.epalmpay.mapper.TradeOfflineMapper;
import com.epalmpay.mapper.YsFlowChargeOrderMapper;
import com.epalmpay.mapper.YsOilcardMapper;
import com.epalmpay.mapper.YsOilcardMemberMapper;
import com.epalmpay.mapper.YsOilcardOrderMapper;
import com.epalmpay.mapper.YsOilcardRechargeInfoMapper;
import com.epalmpay.mapper.YsOilcardRepOrderMapper;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.PayQuickPaymentPay;
import com.epalmpay.payplat.PayQuickPaymentRechargeSubmit;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.service.jobservice.IProfitStatisService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.service.yunstream.IOilcardOrderService;
import com.epalmpay.usercenter.UserAuthApi;
import com.epalmpay.util.Const;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.HttpClientUtil;
import com.epalmpay.util.Response;
import com.epalmpay.util.Tools;
import com.epalmpay.util.payplat.MapUtil;
import com.epalmpay.util.SysUtils;
import com.epalmpay.util.payplat.UtilFun;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;

import me.chanjar.weixin.common.exception.WxErrorException;






/**
 * @author fei
 * @Time：2017年5月24日 下午1:37:18
 * @version 1.0
 */
@Service("OilcardOrderService")
public class OilcardOrderServiceImpl implements IOilcardOrderService {

	private static Logger logger = LoggerFactory.getLogger(OilcardOrderServiceImpl.class);

	private static String BC_ORDER_FLAG = "BC";



	
	@Value("${PAY.OILCARD_RECHARGE_URL}") 
	protected String OILCARD_RECHARGE_URL;
	
	@Value("${PAY.OILCARD_RECHARGE_URL2}") 
	protected String OILCARD_RECHARGE_URL2;
	
	@Value("${PAY.WXFLOWSPAY_NOTIFY_URL}") 
	protected String WXFLOWSPAY_NOTIFY_URL;
	
	@Value("${PAY.WXPAY_NOTIFY_URL}") 
	protected String WXPAY_NOTIFY_URL;
	
	@Value("${PAY.OILALIPAY_NOTIFY_URL}") 
	protected String OILALIPAY_NOTIFY_URL;
	
	@Value("${PAY.FLOWSALIPAY_NOTIFY_URL}") 
	protected String FLOWSALIPAY_NOTIFY_URL;
	
	@Value("${PAY.OILCHARGE_LASTTIME}") 
	protected String OILCHARGE_LASTTIME;
	
	@Value("${PAY.OILCHARGE_STARTTIME}") 
	protected String OILCHARGE_STARTTIME;
	
	@Resource
	private IMemberService memberService;
	
	@Resource
	private YsOilcardOrderMapper oilcardOrderMapper;
	
	@Resource
	private YsOilcardRechargeInfoMapper oilcardRechargeInfoMapper;
	
	@Resource
	private YsOilcardRepOrderMapper oilcardRepOrderMapper;
	@Resource
	private YsOilcardMapper oilcardMapper;
	
	@Resource
	private TradeOfflineMapper tradeOfflineMapper;
	
	@Resource
	private GroupMapper groupMapper;
	
	@Resource
	private MemberMapper memberMapper;
	
	@Resource
	private MemberCardMapper memberCardMapper;
	
	@Resource
	private YsOilcardMemberMapper ysOilcardMemberMapper;
	
	@Resource
	private YsFlowChargeOrderMapper flowChargeMapper;
	
	
	@Resource
	private StatisOilChargeMapper statisOilChargeMapper;
	
	@Resource
	private StatisFlowChargeMapper statisFlowChargeMapper;
	
	
	@Resource
	private GroupPayconfigMapper groupPayconfigMapper;
	
	@Resource
	private  IProfitStatisService profitStatisService;
	
	@Resource
	private IWalletService walletService;
	
	@Override
	public Response insertOilcardOrder(CreateOilOrderInDTO oilcardOrder) {
		//查询套餐信息
		Response baseResult = new Response();
		Long oilcardId=oilcardOrder.getOilcardId();
		//
		Member member=memberMapper.selectByPrimaryKey(oilcardOrder.getMemberId());
		if(member==null){
			baseResult.setStatus(false);
			baseResult.setMessage("用户不存在");
			return baseResult;
		}
		YsOilcard oilcard = oilcardMapper.selectByPrimaryKey(oilcardId);
		if(oilcard == null){
			logger.info("id 为"+oilcardId+"的油卡充值套餐不存在");
			baseResult.setStatus(false);
			baseResult.setMessage("id 为"+oilcardId+"的油卡充值套餐不存在");
			return baseResult;
		}
		Integer amount=oilcardOrder.getAmount();
		int maxAmount=	canRechargeAmount(member.getThirdUserId(), oilcardOrder.getBusinessCode());
		//计算支付金额
		YsOilcardOrder ysOilcardOrder=new YsOilcardOrder();
		
		ysOilcardOrder.setOilcardNumber(oilcardOrder.getOilcardNumber());
		ysOilcardOrder.setPaymentType(oilcardOrder.getPaymentType());
		ysOilcardOrder.setOilcardOwner(oilcardOrder.getOilcardOwner());
		ysOilcardOrder.setOilcardType(oilcardOrder.getOilcardType());
		ysOilcardOrder.setOilcardPhone(oilcardOrder.getOilcardPhone());
//		if(oilcard.getType()==0){
//			//支付金额
//			Integer paymentNum=recaultePayAmount(maxAmount,amount,oilcard);
//			ysOilcardOrder.setPaymentAmount(paymentNum);
//			ysOilcardOrder.setRechargeAmount(amount);//充值金额
//		}else{
//			//支付金额
//			ysOilcardOrder.setPaymentAmount(amount*oilcard.getCountNum()*oilcard.getDiscount()/1000);
//			ysOilcardOrder.setRechargeAmount(amount*oilcard.getCountNum());//充值金额
//		}
		
		Integer paymentNum=recaultePayAmount(maxAmount,amount,oilcard);
		ysOilcardOrder.setPaymentAmount(paymentNum*oilcard.getCountNum());
		ysOilcardOrder.setRechargeAmount(amount*oilcard.getCountNum());//充值金额
		oilcardOrder.setOilcardType(oilcard.getOilcardType());//油卡类型  ZSH OR ZSY
		// 生成订单ID 订单编号生成规则：油卡类型+时间到豪秒+4位随机数
		String orderId = SysUtils.createOrderId(oilcardOrder.getOilcardType());
		logger.info("生成订单号" + orderId);
		ysOilcardOrder.setOilcardOrdernum(orderId);
		//未支付状态
		ysOilcardOrder.setPaymentStatus(1);
		ysOilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.unpay.getType());
		ysOilcardOrder.setOilcardPackageId(SysUtils.Object2Long(oilcardId));
		ysOilcardOrder.setOrderPackageType(oilcard.getType());
		ysOilcardOrder.setOrderCreateTime(new Date());
		ysOilcardOrder.setMemberId(member.getThirdUserId());
		ysOilcardOrder.setOilcardType(oilcardOrder.getOilcardType());
		int num = oilcardOrderMapper.insert(ysOilcardOrder);
		if(num>=0){
			baseResult.format(true, maxAmount,"生成订单成功" , ysOilcardOrder);
		}else{
			logger.info("插入数据失败");
			baseResult.setStatus(false);
			baseResult.setMessage("数据库操作失败");	
		}
		return baseResult;
	}

	/**
	 * 待完成
	 * @param maxAmount
	 * @param amount
	 * @param oilcard
	 * @return
	 */
	private Integer recaultePayAmount(int maxAmount, Integer amount, YsOilcard oilcard) {
		if(maxAmount>=amount){
			//全部优惠
			return amount*oilcard.getDiscount()/1000;
		}else if(maxAmount>0){
			//部分优惠
			return (amount-maxAmount)+maxAmount*oilcard.getDiscount()/1000;
		}
		return amount;
	}


	@Override
	public YsOilcardOrder findOilOrderInfo(String oilcardOrderNum){
		YsOilcardOrder order = oilcardOrderMapper.selectByOilcardOrdernum(oilcardOrderNum);
		if(order==null){
			String orderId = SysUtils.createOrderId("ZSH");
			if(orderId.length()<oilcardOrderNum.length()){
				oilcardOrderNum=oilcardOrderNum.substring(0, orderId.length());
			}
			order = oilcardOrderMapper.selectByOilcardOrdernumBC(oilcardOrderNum);
		}
       return order;
	}
	
	@Override
	public boolean paySuccessCommon(YsOilcardOrder oilcardOrder,Integer payType) {
		
		//未查询到该订单，直接返回
		//支付状态，当状态为2时，代表已支付成功
		if ( oilcardOrder.getPaymentStatus()!=null && oilcardOrder.getPaymentStatus()==2) {
			logger.info("service of pay the order number " + oilcardOrder.getOilcardOrdernum() + " is payments");
			return false;
		}
		
		
		TradeOffline tradeOffline=tradeOfflineMapper.selectByPrimaryKey(oilcardOrder.getPayOrderId());
		if(tradeOffline==null){
			logger.info("交易记录不存在 " + oilcardOrder.getOilcardOrdernum() + " is payments");
			return false;
		}
		
		if(payType!=null){
			tradeOffline.setPayType(payType.byteValue());
			oilcardOrder.setPaymentType(payType);
		}
		
		tradeOffline.setMemo("SUCCESS");
		tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
		this.tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
		//设置支付成功状态
		oilcardOrder.setPaymentStatus(2);
		oilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.paied.getType());//表示已支付
		
		int i = oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
		
		//更新这个套餐的销量
		YsOilcard ysOilcard=oilcardMapper.selectByPrimaryKey(oilcardOrder.getOilcardPackageId());
		ysOilcard.setSaleAmount(ysOilcard.getSaleAmount()+1);
	
		oilcardMapper.updateByPrimaryKey(ysOilcard);
		if (i == 0) {
			logger.info("service of pay the order number " + oilcardOrder.getOilcardOrdernum() + " update fail");
		} else {
			logger.info(
					"service of pay the order number " + oilcardOrder.getOilcardOrdernum() + " update succeed");
		}
		return i>0;
	}


	@Override
	public List<YsOilcardOrder> selectMonthOrderList(Long memberId, String monthTime) {
		Member member=memberMapper.selectByPrimaryKey(memberId);
		
		return oilcardOrderMapper.selectMonthOrder(member.getThirdUserId(),monthTime);
	}

	@Override
	public Response oilChargeOrderWeixinPay(Long orderId, Integer price, Long memberId, String groupId, String ip) {
		Response request = new Response();
		Group businessBase = this.groupMapper.selectGroupByPayCode(groupId);
		Member member = this.memberMapper.selectByPrimaryKey(memberId);
		if (businessBase == null || member == null || member.getGroupId().longValue() != businessBase.getId().longValue()) {
			/**
			 * 会员不是当前商户的
			 */
			return request.format(false, 0, "非法操作", null);
		}

		YsOilcardOrder oilcardOrder = oilcardOrderMapper.selectByPrimaryKey(orderId);
		if (!oilcardOrder.getMemberId().equals(member.getThirdUserId())) {
			/**
			 * 订单不是当前会员的
			 */
			return request.format(false, 0, "非法操作", null);
		}
		if (oilcardOrder.getPaymentStatus().byteValue() == 2) {
			/**
			 * 订单已经支付过了
			 */
			return request.format(false, 10, "已经支付", null);
		}

		if (!oilcardOrder.getPaymentAmount().equals(price)) {
			/**
			 * 订单金额不匹配
			 */
			return request.format(false, 0, "订单金额不一至，支付失败" + oilcardOrder.getPaymentAmount() + ":::" + price, null);
		}

		TradeOffline order = null;
		String orgOrderNum = UtilFun.createOrderNum();
		if (oilcardOrder.getPayOrderId() == null) {
			order = this.initializeOrder(BizEnum.TransactionType.Consumption, BizEnum.PaymentType.WebChat, member, price, orgOrderNum,"OilRecharge");
		} else {
			order = tradeOfflineMapper.selectByPrimaryKey(oilcardOrder.getPayOrderId());
			order.setGmtModified(new Date());
			order.setPayType( (byte)BizEnum.PaymentType.WebChat.getType());
		}
		
		oilcardOrder.setPayOrderId(order.getId());
		oilcardOrder.setPaymentType(BizEnum.PaymentType.WebChat.getType());
		oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);

		// 1467792702
		// 57393e5a92a944d67289cc2264ea58d9
		try {			
			String notifyUrl=Global.HOME_URL+WXPAY_NOTIFY_URL;
			WxPayUnifiedOrderResult unifiedorderResult=wxpayUnifiedOrder("云流-油卡充值", oilcardOrder.getOilcardOrdernum(), price, ip, notifyUrl,businessBase.getId());
			if ("SUCCESS".equals(unifiedorderResult.getReturnCode())) {
					if ("SUCCESS".equals(unifiedorderResult.getResultCode())) {
						Map<String, Object> result = new HashMap<String, Object>();
						result.put("appid", unifiedorderResult.getAppid());
						result.put("mch_id", unifiedorderResult.getMchId());
						result.put("nonce_str", unifiedorderResult.getNonceStr());
						result.put("sign", unifiedorderResult.getSign());
						result.put("prepay_id", unifiedorderResult.getPrepayId());
						result.put("trade_type", unifiedorderResult.getTradeType());

						return request.format(true, 1, "下单成功", result);
					} else {
						return request.format(false, 0, unifiedorderResult.getResultCode() + ":" + unifiedorderResult.getErrCodeDes(), null);
					}
				}

				return request.format(false, 0, unifiedorderResult.getReturnMsg(), null);
		} catch (WxErrorException e) {
			
			e.printStackTrace();
			return request.format(false, 0, "微信支付参数错误", null);
		}
	}

	@Override
	public Response oilChargeOrderAliPay(Long orderId, Integer price, Long memberId, String groupId,String ip) {
		Response request = new Response();
		Group businessBase = this.groupMapper.selectGroupByPayCode(groupId);
		Member member = this.memberMapper.selectByPrimaryKey(memberId);
		if (businessBase == null || member == null || member.getGroupId().longValue() != businessBase.getId().longValue()) {
			/**
			 * 会员不是当前商户的
			 */
			return request.format(false, 0, "非法操作", null);
		}


		
		
		YsOilcardOrder oilcardOrder=oilcardOrderMapper.selectByPrimaryKey(orderId);
		if(!oilcardOrder.getMemberId().equals(member.getThirdUserId())){
			/**
			 * 订单不是当前会员的
			 */
			return request.format(false,0,"非法操作", null);
		}
		if(oilcardOrder.getPaymentStatus().byteValue()==2){
			/**
			 * 订单已经支付过了
			 */
			return request.format(false,10,"已经支付", null);
		}
		
		if(!oilcardOrder.getPaymentAmount().equals(price)){
			/**
			 * 订单金额不匹配
			 */
			return request.format(false,0,"订单金额不一至，支付失败"+oilcardOrder.getPaymentAmount()+":::"+price,null);
		}
		TradeOffline order = null;
		String orgOrderNum = UtilFun.createOrderNum();
		if (oilcardOrder.getPayOrderId() == null) {
			order = this.initializeOrder(BizEnum.TransactionType.Consumption, BizEnum.PaymentType.AliPay, member, price, orgOrderNum,"OilRecharge");
		} else {
			order = tradeOfflineMapper.selectByPrimaryKey(oilcardOrder.getPayOrderId());
			order.setGmtModified(new Date());
			order.setPayType( (byte)BizEnum.PaymentType.AliPay.getType());
		}
		
		oilcardOrder.setPayOrderId(order.getId());
		oilcardOrder.setPaymentType(BizEnum.PaymentType.AliPay.getType());
		oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
		Map<String, Object> result = new HashMap<String, Object>();
		String notifyUrl=Global.HOME_URL+OILALIPAY_NOTIFY_URL;
		result.put("notifyUrl", notifyUrl);
		result.put("orderId", order.getId());
		result.put("merchantOrderNum", oilcardOrder.getOilcardOrdernum());
		 return request.format(true, 1, "下单成功",result );
	}
	
	@Override
	public Response oilChargeOrderPay(Long orderId, Integer price, String payPwd,
			Long memberId, String groupId) throws ApplicationException {
		Response request = new Response();
		Group group = this.groupMapper.selectGroupByPayCode(groupId);
		Member member = this.memberMapper.selectByPrimaryKey(memberId);
		if (group == null || member == null || member.getGroupId().longValue() != group.getId().longValue()) {
			/**
			 * 会员不是当前商户的
			 */
			return request.format(false, 0, "非法操作", null);
		}
		
		YsOilcardOrder oilcardOrder=oilcardOrderMapper.selectByPrimaryKey(orderId);
		if(!oilcardOrder.getMemberId().equals(member.getThirdUserId())){
			/**
			 * 订单不是当前会员的
			 */
			return request.format(false,0,"非法操作", null);
		}
		if(oilcardOrder.getPaymentStatus().byteValue()==2){
			/**
			 * 订单已经支付过了
			 */
			return request.format(true,1,"已经支付成功");
		}
		
		if(!oilcardOrder.getPaymentAmount().equals(price)){
			/**
			 * 订单金额不匹配
			 */
			return request.format(false,0,"订单金额不一至，支付失败"+oilcardOrder.getPaymentAmount()+":::"+price);
		}
		/**
		 * 防止订单号 重复，进行刷新
		 */
		reflashOilcardOrder(oilcardOrder,groupId);
		TradeOffline order=null;
		String orgOrderNum =  oilcardOrder.getOilcardOrdernum();
		if (oilcardOrder.getPayOrderId() == null) {	
			order = this.initializeOrder(BizEnum.TransactionType.Consumption, BizEnum.PaymentType.Wallet, member, price, orgOrderNum,"OilRecharge");
		} else {
			order = tradeOfflineMapper.selectByPrimaryKey(oilcardOrder.getPayOrderId());
			order.setGmtModified(new Date());
			order.setPayType( (byte)BizEnum.PaymentType.Wallet.getType());
			order.setPayOrderid(oilcardOrder.getOilcardOrdernum());
		}
		oilcardOrder.setPayOrderId(order.getId());
		 String SysTraceNum=DateUtil.getSdfTimes()+Tools.getRandomNum(4);
		  PayResult result =walletService.updatePayConsumption(member.getVirtualCard(), group.getPayGroupCode(), member.getUserId(),
				  price, SysTraceNum, payPwd,null,order.getOrderId());
				if (!result.getRespCode().equals("0000")) {
					throw new ApplicationException(Rescode.FAIL, result.getMsgTxt());
				}
		
		oilcardOrder.setPaymentType(BizEnum.PaymentType.Wallet.getType());
		oilcardOrder.setPayOrderId(order.getId());
		oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
		if(result==null || result.getVerificationStatus().byteValue()==Global.FALSE){
			return request.format(false, 0, "支付失败,通信异常");
		}
		
		if(IPayAPI.Success.equals(result.getRespCode())){
			order.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
			order.setMemo(result.getMsgTxt());
			this.tradeOfflineMapper.updateByPrimaryKeySelective(order);
			/**
			 * 支付成功
			 */				
			//支付状态，当状态为2时，代表已支付成功
			if ( oilcardOrder.getPaymentStatus()!=null && oilcardOrder.getPaymentStatus()==2) {
				logger.info("service of pay the order number " + oilcardOrder.getOilcardOrdernum() + " is payments");
				
				return request.format(false,0,"不能重复支付");
			}
			//设置支付成功状态
			oilcardOrder.setPaymentStatus(2);
			oilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.paied.getType());
			oilcardOrder.setPaymentOrderId(result.getOrderId());
			oilcardOrder.setPaymentTime(new Date());
			oilcardOrder.setPaymentResultCord("支付成功");
			int i = oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
			
			//更新这个套餐的销量
			YsOilcard ysOilcard=oilcardMapper.selectByPrimaryKey(oilcardOrder.getOilcardPackageId());
			ysOilcard.setSaleAmount(ysOilcard.getSaleAmount()+1);
			oilcardMapper.updateByPrimaryKey(ysOilcard);
			
			if (i == 0) {
				logger.info("service of pay the order number " + oilcardOrder.getOilcardOrdernum() + " update fail");
			} else {
				logger.info(
						"service of pay the order number " + oilcardOrder.getOilcardOrdernum() + " update succeed");
			}	
			try {
				memberService.insertMemberTradeDataAsyn(order.getMemberId(), oilcardOrder.getPaymentAmount());
				 Map<String ,String> t=oilCardRecharge(oilcardOrder.getOilcardOrdernum());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return request.format(true,1,"已经支付成功",null,orgOrderNum);
		}else{
			order.setTransactionStatus((byte)BizEnum.TransactionStatus.Failure.getType());
			order.setMemo(result.getMsgTxt());
			this.tradeOfflineMapper.updateByPrimaryKeySelective(order);
		} 
		return request.format(false,0,IPayAPI.getErrorText(result, result.getMsgTxt()));
		
	}
	/**
	 * 防止订单号重复，更新订单号 从0-Z补位
	 * @param oilcardOrder
	 * @param groupId
	 */
	private void reflashOilcardOrder(YsOilcardOrder oilcardOrder, String groupId) {
		
		String orderId = SysUtils.createOrderId(oilcardOrder.getOilcardType());
		String oldOrderCode =oilcardOrder.getOilcardOrdernum();
		if(oldOrderCode.length()==orderId.length()){
	    	//还没有更新过
	    	String newCode=oldOrderCode+"1";
	    	oilcardOrder.setOilcardOrdernum(newCode);
			oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
	    }else{
	    	//表示曾经补位
	    	char last=oldOrderCode.charAt(oldOrderCode.length()-1);
	    	if(last=='9'){
	    		last='A';
	    	}else{
	    		last=(char) (last+1);
	    	}
	    	String newCode=oldOrderCode.substring(0, oldOrderCode.length()-1)+last;
	    	oilcardOrder.setOilcardOrdernum(newCode);
			oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
	    }
		
	}
	
	public TradeOffline oilCrdPayNotify(String orderNum,String transResult,String orderNo){
		logger.info("=============================油卡通知^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
		logger.info("充值回调通知:rechargeNotify");
		if(orderNum==null || transResult==null){ 
			logger.error("回调参数不全");
			return null;
		}
		YsOilcardOrder oilcardOrder=findOilOrderInfo(orderNum);
		
		TradeOffline tradeOffline=tradeOfflineMapper.selectByPrimaryKey(oilcardOrder.getPayOrderId());
		if("1".equals(transResult)){
			/**
			 * 支付成功
			 */				
			//支付状态，当状态为2时，代表已支付成功
			if ( oilcardOrder.getPaymentStatus()!=null && oilcardOrder.getPaymentStatus()==2) {
				logger.info("service of pay the order number " + oilcardOrder.getOilcardOrdernum() + " is payments");
				
				return null;
			}
			
			//设置支付成功状态
			oilcardOrder.setPaymentStatus(2);
			oilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.paied.getType());
			oilcardOrder.setPaymentOrderId(orderNo);
			oilcardOrder.setPaymentTime(new Date());
			oilcardOrder.setPaymentResultCord("支付成功");
			oilcardOrder.setPaymentType(BizEnum.PaymentType.NetBankCardQuick.getType());
			int i = oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
			//更新这个套餐的销量
			YsOilcard ysOilcard=oilcardMapper.selectByPrimaryKey(oilcardOrder.getOilcardPackageId());
			ysOilcard.setSaleAmount(ysOilcard.getSaleAmount()+1);
			oilcardMapper.updateByPrimaryKey(ysOilcard);
			if (i == 0) {
				logger.info("service of pay the order number " + oilcardOrder.getOilcardOrdernum() + " update fail");
			} else {
				logger.info(
						"service of pay the order number " + oilcardOrder.getOilcardOrdernum() + " update succeed");
			}
			//更新订单信息 
			tradeOffline.setPayType((byte)BizEnum.PaymentType.NetBankCardQuick.getType());
			tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
			tradeOffline.setMemo("支付成功");
			this.tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

			try {
				logger.info("----------------------油卡购买会员总交易数1-----------------------------------");
				memberService.insertMemberTradeDataAsyn(tradeOffline.getMemberId(), oilcardOrder.getPaymentAmount());	
				logger.info("----------------------油卡购买会员总交易数1-----------------------------------");
			 Map<String ,String> result=oilCardRecharge(oilcardOrder.getOilcardOrdernum());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return tradeOffline;
		}else{
			//更新订单信息 
			tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Failure.getType());
			tradeOffline.setMemo("支付失败");
			this.tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
			return null;
		} 
		
	}
	/**
	 * 生成交易订单
	 * @param type			订单类型
	 * @param orderUserId	订单用户
	 * @param orderGroupId	订单商户
	 * @return
	 */
	public TradeOffline initializeOrder(BizEnum.TransactionType type,BizEnum.PaymentType payType,Member member,Integer amount ,String OrgOrderNum,String memo){
		 //插入线下交易表
        TradeOffline record = new TradeOffline();
        
        record.setMemo(memo);
	    record.setDetail(memo);//详情
	    record.setTransactionType((byte)type.getType());
	    
	    record.setGmtCreate(new Date());
        record.setGmtModified(new Date());
        record.setGroupId(member.getGroupId());
        record.setOrderId(OrgOrderNum); 
        record.setPayerId(member.getId());//会员id
        record.setPayerName(member.getName());
        record.setPayerType((byte) CommonEnum.UserType.User.getType());
        record.setReceiverId(String.valueOf(member.getId()));//接收者id
        record.setReceiverName(member.getName());//接收者
		record.setReceiverType((byte) CommonEnum.UserType.User.getType());
        record.setSubType((byte)BizEnum.PaymentScene.Online.getType());//支付场景
        record.setOrderAmount(Integer.valueOf(amount)); 
        record.setDiscountAmount(0);//折扣金额
        record.setRealAmount(record.getOrderAmount());//实付金额
        record.setPayType((byte)payType.getType());
//        record.setRelatedActivityId(null);//关联活动
        record.setTransactionStatus((byte)BizEnum.TransactionStatus.WaitingForPay.getType());
        record.setIsWallet(true);
        record.setTermSerial(null);
        record.setMerchantNo(null);//商户号
        record.setTerminalNo(null);//商户终端号
        record.setTransNo(null); //交易流水号
        record.setTransOrderNo(null);//交易机构订单号
        record.setPayAccount("");//支付卡号
        record.setScanOrganization(null);//扫码付入网机构
        record.setCrcodeStr(null); 
        record.setOldOrderId(null); 
        record.setDividableAmount(0);//可分润金额
        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        record.setPayOrderid(OrgOrderNum);
        record.setPayBakOrderid(null);
        record.setInNetCompany(null);//入网机构
        tradeOfflineMapper.insertSelective(record);
        return record;
		
	}

	@Override
	public int canRechargeAmount(String ysUserId,String businessCode ) {
		Group group=this.groupMapper.selectGroupByPayCode(businessCode);
		
		Member member=memberMapper.selectByThirdUserId(ysUserId);
		Integer maxAmount = ysOilcardMemberMapper.selectYsDiscountLimitAmount(member.getId());
		if(maxAmount==null){
			return 999999999;
		}else{
			String startDate=SysUtils.formatDate(new Date(), "yyyy-MM");
			//  业务需求变更，以前是只看及时充值的充值金额 
			//Integer hadRechargeAmount= oilcardOrderMapper.findRechargeAmount(ysUserId,startDate);
			Integer hadRechargeAmount= oilcardRechargeInfoMapper.findRechargeAmount(ysUserId,startDate);
			//现在包含本月套餐充值的金额
			if(hadRechargeAmount!=null){
				return  maxAmount-hadRechargeAmount;
			}
			return maxAmount;
		}		
	}
	
	@Override
	public int inPackageOrder(String memberId, String businessCode) {
		String date = SysUtils.formatDate("yyyy-MM-dd");
		List<YsOilcardRechargeInfo> oilcardRechargeInfos = oilcardRechargeInfoMapper.findUnRechargeByPackageOrder(memberId, date);
		if (oilcardRechargeInfos != null && oilcardRechargeInfos.size() > 0) {
			return 1;
		}
		return 0;
	}
	

	@Override
	public YsOilcardOrder finishOidCardOrderById(Long orderId) {
		
		return oilcardOrderMapper.selectByPrimaryKey(orderId);
	}

	

	@Override
	public List<OilcardChargeOrderBean> listOilcardCharge(OilcardChargeListInDTO listInDTO, Page page) {
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("businessId", listInDTO.getGroupId());
		map.put("oilcardType", listInDTO.getOilcardType());
		map.put("datefrom",  listInDTO.getDatefrom());
		map.put("dateto",  listInDTO.getDateto());
		map.put("username",  listInDTO.getUsername());
		map.put("denomination",  listInDTO.getDenomination());	
		map.put("orderNum",  listInDTO.getOrderNum());	
		map.put("paymentStatus",  listInDTO.getPaymentStatus());
		map.put("orderStatus",  listInDTO.getOrderStatus());
        int sumCount = oilcardOrderMapper.selectOilChargeOrderCounts(map);
		
		page.setTotalResult(sumCount);
		if(sumCount<=0){
			return new ArrayList<OilcardChargeOrderBean>();
		}
		map.put("limit", page.getShowCount());
		map.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		return this.oilcardOrderMapper.selectOilChargeOrder(map);
	
	}

	@Override
	public YsOilcardOrder findOilChargeOrderInfo(Long orderId) {
		
		return oilcardOrderMapper.selectByPrimaryKey(orderId);
	}

	@Override
	public YsOilcardRechargeInfo findOilReChargeOrderInfo(Long oilCardChargeId) {
		
		return  oilcardRechargeInfoMapper.selectByPrimaryKey(oilCardChargeId);
	}
	
	@Override
	public List<OilcardRechargeInfoBean> listOilcardChargeByMemberCardId(OilCardOrderReChargeInDTO listInDTO, Page page) {
		
		YsOilcardMember ysOilcardMember= ysOilcardMemberMapper.selectByPrimaryKey(listInDTO.getMemberCardId());
		
		Member member=memberMapper.selectByPrimaryKey(ysOilcardMember.getMemberId());
		String ysUserId=member.getThirdUserId();
		

		Map<String, Object> map = new HashMap<String, Object>();
		//map.put("businessId", member.getGroupId());
		map.put("datefrom",  listInDTO.getDatefrom());
		map.put("dateto",  listInDTO.getDateto());
		map.put("ysUserId",  ysUserId);
		map.put("groupId",  member.getGroupId());
		
		map.put("oilcardNumber",  ysOilcardMember.getOilcardNumber());
		map.put("oilcardName",  ysOilcardMember.getOilcardName());
        int sumCount = oilcardRechargeInfoMapper.selectOilChargeInfoCounts(map);
		
		page.setTotalResult(sumCount);
		if(sumCount<=0){
			return new ArrayList<OilcardRechargeInfoBean>();
		}
		map.put("limit", page.getShowCount());
		map.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		return oilcardRechargeInfoMapper.selectOilChargeInfo(map);
	}
	/**
	    * 及时充值订单只有一条充值记录
	    * @param oilcardOrderId
	    * @return
	 * @throws Exception 
	    */
	@Override
	public YsOilcardRechargeInfo findOilcardRechargeInfoByOid(Long oilcardOrderId) throws Exception {
		List<YsOilcardRechargeInfo> oilcardRechargeInfos=	oilcardRechargeInfoMapper.selectByOilCardorderId(oilcardOrderId);
		
		if(oilcardRechargeInfos!=null){
			if(oilcardRechargeInfos.size()>1){
				throw new Exception("数据异常");
			}else if(oilcardRechargeInfos.size()==1){
				return oilcardRechargeInfos.get(0);
			}
		}
		return null;
	}
	/**
	    * 套餐充值订单有多条充值记录
	    * @param oilcardOrderId
	    * @return
	    */
	@Override
	public List<OilcardRechargeInfoBean> findPackageORechargeInfoByOid(Long oilcardOrderId) {
		List<OilcardRechargeInfoBean> oilcardRechargeInfos=	 oilcardRechargeInfoMapper.selectInfoByOilCardorderId(oilcardOrderId);
		return oilcardRechargeInfos;
	}



	



	
	
	@Override
	public  Map<String ,String> oilCardRecharge(String oilcardOrdernum) throws Exception {
		
		 Map<String ,String> result=new HashMap<String,String>();		
		//判断支付金额和套餐应付金额是否一致
		YsOilcardOrder oilcardOrder=findOilOrderInfo(oilcardOrdernum);
		
		if(oilcardOrder==null){
			result.put("code", "0032");
			result.put("msg", "订单不存在");
			return result;
		}
		
		if(oilcardOrder.getPaymentStatus().intValue()!=2){
			result.put("code", "0032");
			result.put("msg", "订单未支付");
			return result;
		}
		
		if(oilcardOrder.getOrderStatus().intValue()!=1){
			result.put("code", "0032");
			result.put("msg", "订单已充值");
			return result;
		}
		String oilcardType = oilcardOrder.getOilcardType();
		//Oilcar oilcard = oilcardMapper.selectCardByAmount();
		YsOilcard oilcard = oilcardMapper.selectByPrimaryKey(oilcardOrder.getOilcardPackageId());
		int  countNum=oilcard.getCountNum();
		//插入充值订单
		Integer rechargeAmount = oilcardOrder.getRechargeAmount()/countNum;
		
		YsOilcardRechargeInfo oilcardOrderInfo=new YsOilcardRechargeInfo();
		oilcardOrderInfo.setAddedValueStatus("1");
		oilcardOrderInfo.setOilcardOrderId(oilcardOrder.getId());
		oilcardOrderInfo.setRechargeAmount(rechargeAmount);
		oilcardOrderInfo.setRechargeStatus(0);
		oilcardOrderInfo.setRechargeReqTime(new Date());
		oilcardRechargeInfoMapper.insert(oilcardOrderInfo);
		if(oilcardOrder.getOrderPackageType().intValue()==1){
			
			/**
			 * 添加后续需要充值的部分
			 */
			
			for(int i=1;i<countNum;i++){
				//套餐充值
				YsOilcardRechargeInfo tOilcardRechargeInfo=new YsOilcardRechargeInfo();
				tOilcardRechargeInfo.setAddedValueStatus("1");
				tOilcardRechargeInfo.setOilcardOrderId(oilcardOrder.getId());
				tOilcardRechargeInfo.setRechargeStatus(0);
				tOilcardRechargeInfo.setRechargeAmount(rechargeAmount);
				tOilcardRechargeInfo.setRechargeReqTime(SysUtils.getNextMonthStart(i));
				oilcardRechargeInfoMapper.insert(tOilcardRechargeInfo);
			}
		}
		
		if(oilcard == null||!oilcard.getOilcardType().equals(oilcardType) ){
			logger.info("订单号"+oilcardOrder.getOilcardOrdernum()+"充值金额有误！无法进行充值！");
			oilcardOrderInfo.setRechargeStatus(4);
			oilcardRechargeInfoMapper.updateByPrimaryKey(oilcardOrderInfo);
			result.put("code", "0032");
			result.put("msg", "支付金额有误，无法进行充值");
			oilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.need_recharge_5.getType());//需要补充值
			oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
			return result ;
		}
		//查询 这个渠道的相关信息
		Member member=memberMapper.selectByThirdUserId(oilcardOrder.getMemberId());
		GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(member.getGroupId());
		if(groupPayconfig==null){
			logger.info("订单号"+oilcardOrder.getOilcardOrdernum()+"充值金额有误！无法进行充值！");
			oilcardOrderInfo.setRechargeStatus(4);
			oilcardRechargeInfoMapper.updateByPrimaryKey(oilcardOrderInfo);
			result.put("code", "0032");
			result.put("msg", "充值参数未配置");
			oilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.need_recharge_5.getType());//需要补充值
			oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
			return result ;
		}
		
		String outTradeOrderNum=createRechargeOrderId(oilcardOrder.getOilcardType());
		result=this.finishSumitOilcardOrder(groupPayconfig, outTradeOrderNum, oilcardOrderInfo, oilcardOrder);
		if("0000".equals(result.get("code"))){
			oilcardOrderInfo.setRechargeStatus(1);//1、发送充值请求成功；
		  if(oilcardOrder.getOrderPackageType()==1){
			oilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.in_2.getType());
		  }else{
			oilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.complate_3.getType());//如果充值成功 ，表示订单完成
		  }
		}else if("9999".equals(result.get("code"))) {
			//修改第二天时间进行充值
			oilcardOrderInfo.setRechargeStatus(0);//待充值
			//oilcardOrderInfo.setRechargeReqTime(DateUtil.getDateNext(new Date(), 1));//发送充值请求时间
			oilcardOrderInfo.setRechargeReqTime(new Date(System.currentTimeMillis()+6*60*60*1000));//发送充值请求时间
			oilcardRechargeInfoMapper.updateByPrimaryKey(oilcardOrderInfo);
			return result;
		}else {
			oilcardOrderInfo.setRechargeStatus(2);//2、发送充值请求失败；
			oilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.need_recharge_5.getType());//需要补充值
		}
		oilcardOrderInfo.setOilcardRechargeOrderNum(outTradeOrderNum);
		oilcardOrderInfo.setOilcardRechargeResultCord(result.get("code")+":"+result.get("msg"));		
		oilcardOrderInfo.setRechargeReqTime(new Date());//发送充值请求时间
		oilcardRechargeInfoMapper.updateByPrimaryKey(oilcardOrderInfo);
		oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
		return result;
	}
//	/**
//	 * 完成油卡充值提交 1.0
//	 * @return
//	 */
//	private Map<String, String> finishSumitOilcardOrder(GroupPayconfig groupPayconfig,String outTradeOrderNum ,YsOilcardRechargeInfo oilcardOrderInfo,YsOilcardOrder oilcardOrder) {
//		Map<String, String> params = new LinkedHashMap<String, String>();
//		params.put("appId", groupPayconfig.getAgentAppid());
//		params.put("userId", groupPayconfig.getAgentUserid());
//		params.put("outTradeNo", outTradeOrderNum);
//		params.put("orderSum",String.valueOf( oilcardOrderInfo.getRechargeAmount()/100));
//		params.put("gasAccount", oilcardOrder.getOilcardNumber());
//		params.put("gasOwner", oilcardOrder.getOilcardOwner());
//		params.put("gasType", oilcardOrder.getOilcardType());
//		params.put("phone", oilcardOrder.getOilcardPhone());
//		params.put("sign", md5Sign(params,groupPayconfig.getAgentAppkey()));
////
////		params.put("gasOwner", URLEncoder.encode(params.get("gasOwner"), "UTF-8"));
////		
//		String content = HttpClientUtil.post(OILCARD_RECHARGE_URL, params);	
//		JSONObject obj=JSONObject.parseObject(content);
//		String objCode=obj.getString("code");
//		String msg=obj.getString("msg");
//		logger.info("油卡充值返回信息：" + content);
//		Map<String,String>result=new HashMap<String,String>();
//		result.put("code", objCode);
//		result.put("msg", msg);
//		return result;
//	}

	
	/**
	 * 完成油卡充值提交2.0
	 * @return
	 * @throws Exception 
	 */
	private Map<String, String> finishSumitOilcardOrder(GroupPayconfig groupPayconfig,String outTradeOrderNum 
			,YsOilcardRechargeInfo oilcardOrderInfo,YsOilcardOrder oilcardOrder) throws Exception {
		
		//如果当前充值时间为 晚上
		Map<String,String>result=new HashMap<String,String>();
		String currentTime=DateUtil.fomatDate(new Date(), DateUtil.sdfTimeInfo);
		if(currentTime.compareTo(OILCHARGE_LASTTIME)>0||OILCHARGE_STARTTIME.compareTo(currentTime)>0){
			//不能充值 这段时间不能充值
		   result.put("code","9999");
		   result.put("msg", "当前时间段不能充值");
		   return result;
		}
		Map<String, String> params = new LinkedHashMap<String, String>();
		String userId=groupPayconfig.getAgentUserid();
		params.put("userId",userId );
		params.put("serialno", outTradeOrderNum);
		Integer amount=oilcardOrderInfo.getRechargeAmount();
		String itemId=this.findOilcardGoodsId(amount,oilcardOrder.getOilcardType());
		params.put("itemId",itemId );
		params.put("uid", oilcardOrder.getOilcardNumber());
//		params.put("gasType", oilcardOrder.getOilcardType());
//		params.put("phone", oilcardOrder.getOilcardPhone());
		String dtCreate= SysUtils.formatDate(new Date(), "yyyyMMddHHmmss");
		params.put("dtCreate",dtCreate);
		
		//params.put("sign", md5Sign(params,groupPayconfig.getAgentAppkey()));
		//MD5(dtCreate  itemId serialno uid userId key
		StringBuffer sb = new StringBuffer();
		sb.append(dtCreate)
		.append(itemId)
		.append(outTradeOrderNum)
		.append(oilcardOrder.getOilcardNumber())
		.append(userId)
        .append(groupPayconfig.getAgentAppkey());
		String md5Sign = UtilFun.stringMD5(sb.toString());
		logger.info("油卡充值回调信息：---------》"+sb.toString());
		logger.info("md5Sign---------------->"+md5Sign);
		params.put("sign",md5Sign.toLowerCase() );
		String content = HttpClientUtil.post(OILCARD_RECHARGE_URL2, params);
		
		Map<String, String> map=MapUtil.xmlStringToMap(content);
		logger.info("油卡充值2返回信息：" +map+"........................."+ content);
	
		if("00".equals(map.get("code"))){		
			result.put("code", "0000");	
		}else{
			result.put("code", map.get("code"));
		}
		result.put("msg", map.get("desc"));
		return result;
	}
	/**
	 * 中石化100元：10000
中石化200元：10001
中石化500元：10002
中石化1000元:10003


中石油100元：10004

中石油200元：10005

中石油500元：10006

中石油1000元:10007
	 * @param amount
	 * @param string
	 * @return
	 * @throws Exception 
	 */
	private String findOilcardGoodsId(Integer amount, String oilcardType) throws Exception {
		if(oilcardType.equalsIgnoreCase("ZSH")){
			if(amount.intValue()==10000){
				return "10000";
			}
			if(amount.intValue()==20000){
				return "10001";
			}
			if(amount.intValue()==50000){
				return "10002";
			}
			if(amount.intValue()==100000){
				return "10003";
			}
		} else if(oilcardType.equalsIgnoreCase("ZSY")){
			if(amount.intValue()==10000){
				return "10004";
			}
			if(amount.intValue()==20000){
				return "10005";
			}
			if(amount.intValue()==50000){
				return "10006";
			}
			if(amount.intValue()==100000){
				return "10007";
			}
		}
		throw new Exception("油卡类型不对");
	}

		// 生成订单号
		private String createRechargeOrderId(String oilcardType) {
			StringBuffer sBuffer = new StringBuffer();
			sBuffer.append(oilcardType);
			// 时间，到毫秒
			String dateToString =SysUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS");
			sBuffer.append(dateToString);
			// 生成四位随机数
			sBuffer.append(SysUtils.getFourRandom());
			return sBuffer.toString();
		}
		
		/**
		 * 执行某条固定的充值记录
		 */
		@Override
		public  Map<String ,String> finishOilcardRechargeInfoRecharge(YsOilcardRechargeInfo oilcardOrderInfo) throws Exception {
			
			 Map<String ,String> result=new HashMap<String,String>();		
			 YsOilcardOrder oilcardOrder=oilcardOrderMapper.selectByPrimaryKey(oilcardOrderInfo.getOilcardOrderId());	
			
			String outTradeOrderNum=createRechargeOrderId(oilcardOrder.getOilcardType());
			Member member=memberMapper.selectByThirdUserId(oilcardOrder.getMemberId());
			GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(member.getGroupId());
			result=this.finishSumitOilcardOrder(groupPayconfig, outTradeOrderNum,oilcardOrderInfo,oilcardOrder);
			if(result.get("code").equals("0000")){
				oilcardOrderInfo.setRechargeStatus(1);//1、发送充值请求成功；
			}else if("9999".equals(result.get("code"))) {
				//修改第二天时间进行充值
				oilcardOrderInfo.setRechargeStatus(0);//待充值
				oilcardOrderInfo.setRechargeReqTime(new Date(System.currentTimeMillis()+6*60*60*1000));//发送充值请求时间
				oilcardRechargeInfoMapper.updateByPrimaryKey(oilcardOrderInfo);
				return result;
			}else{
				oilcardOrderInfo.setRechargeStatus(2);//2、发送充值请求失败；
			}
			oilcardOrderInfo.setOilcardRechargeOrderNum(outTradeOrderNum);
			oilcardOrderInfo.setOilcardRechargeResultCord(result.get("code")+":"+result.get("msg"));		
			oilcardOrderInfo.setRechargeReqTime(new Date());//发送充值请求时间
			oilcardRechargeInfoMapper.updateByPrimaryKey(oilcardOrderInfo);
			//重新检查订单状态
			finishCheckOilCardOrderStatus(oilcardOrder.getId());
			return result;
		}
		

	/**
	 * md5 校验码 md5Sign:().
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	private String md5Sign(Map<String, String> params,String agentkey) {
		StringBuffer stringBuffer = new StringBuffer();
		params.forEach((key, value) -> {
			if ("phone".equals(key)) {
				value = value + agentkey;
			}
			stringBuffer.append(key + "=" + value + "&");
		});
		stringBuffer.deleteCharAt(stringBuffer.length() - 1);
		String string = stringBuffer.toString();
		return UtilFun.stringMD5(string);
	}

	/**
	 * 油卡充值回调service 根据订单号最后两位判断是否是补充值订单 根据订单号查询订单数据 更新对应的订单状态
	 */
	@Override
	public YsOilcardOrder rechargeCallBack(String outTradeNo, String orderId, String createTime, int status,String memo ) {
		String bcOrderFlag = outTradeNo.substring(outTradeNo.length() - 2);
		YsOilcardRechargeInfo oilcardRechargeInfo=null;
		
		if (!BC_ORDER_FLAG.equals(bcOrderFlag)) {
			oilcardRechargeInfo = oilcardRechargeInfoMapper.selectByRechargeOrderNum(outTradeNo);
			if (oilcardRechargeInfo == null) {
				logger.info("service of pay the order number " + outTradeNo + " is not found");
				return null;
			}
			if(oilcardRechargeInfo.getRechargeStatus()==3){
				//如果当前油卡充值订单状态 是已成功 不处理
				return  null;
			}
			
		} else {
			YsOilcardRepOrder ocrOrder= oilcardRepOrderMapper.selectByReplenishOrderId(outTradeNo);
			if (ocrOrder == null) {
				logger.info("service of pay the order number " + outTradeNo + " is not found");
				return null;
			}
			 oilcardRechargeInfo = oilcardRechargeInfoMapper.selectByPrimaryKey(ocrOrder.getOilcardRechargeId());
			if (oilcardRechargeInfo == null) {
				logger.info("service of pay the oilcardRechargeInfo  number " + outTradeNo + " is not found");
				return null;
			}
			if(oilcardRechargeInfo.getRechargeStatus()==3){
				//如果当前油卡充值订单状态 是已成功 不处理
				return  null;
			}
			ocrOrder.setRequestStatus(status);
			ocrOrder.setOilcardOrderRechargeId(orderId);
			ocrOrder.setRechargeTime(SysUtils.stringToDate(createTime));
			oilcardRepOrderMapper.updateByPrimaryKey(ocrOrder);
		}
		oilcardRechargeInfo.setOilcardOrderNum(orderId);
		oilcardRechargeInfo.setRechargeTime(SysUtils.stringToDate(createTime));
		oilcardRechargeInfo.setRechargeStatus(status);
		try {
			if(StringUtils.isNotBlank(memo)){
				oilcardRechargeInfo.setOilcardRechargeResultCord(new URLDecoder().decode(memo,"UTF-8"));	
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		oilcardRechargeInfo.setAddedValueStatus("1");
		int i = oilcardRechargeInfoMapper.updateByPrimaryKey(oilcardRechargeInfo);
		if (i == 0) {
			logger.info("service of pay the order number " + oilcardRechargeInfo.getOilcardOrderId() + " update fail");
		} else {
			logger.info(
					"service of pay the order number " + oilcardRechargeInfo.getOilcardOrderId() + " update succeed");
		}
		return finishCheckOilCardOrderStatus(oilcardRechargeInfo.getOilcardOrderId());
	}
	/**
	 * 检查油卡充值 订单状态
	 */
   private YsOilcardOrder finishCheckOilCardOrderStatus(Long oilcardOrderId){
    	//检查这边订单的状态，根据订单号 查询所有的支付详情，如果有 需要补充值的状态 为5 ，如果 都完成为 3 有未充值的 2
		 boolean orderIn=false;
		 List<YsOilcardRechargeInfo>rechargeInfos= oilcardRechargeInfoMapper.selectByOilCardorderId(oilcardOrderId);
	     YsOilcardOrder oilcardOrder=oilcardOrderMapper.selectByPrimaryKey(oilcardOrderId);
		 for(YsOilcardRechargeInfo rechargeInfo:rechargeInfos){
	    	 if((rechargeInfo.getRechargeStatus().intValue()==BizEnum.OilChargeStatus.in_2.getType()||rechargeInfo.getRechargeStatus().intValue()==BizEnum.OilChargeStatus.close_4.getType())&&"1".equals(rechargeInfo.getAddedValueStatus())){
	    		 oilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.need_recharge_5.getType());
	    		 oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
	    		 return oilcardOrder;
	    	 }else if(rechargeInfo.getRechargeStatus()!=3&&rechargeInfo.getRechargeStatus()!=-1){
	    		 orderIn=true;
	    	 }
	     }
	    if(orderIn){
	    	 oilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.in_2.getType());
	    }else{
	    	 oilcardOrder.setOrderStatus(BizEnum.OilChargeStatus.complate_3.getType());
	    }
	    oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
	    return oilcardOrder;
    }
	@Override
	public Map<String ,String> insertReplenish(YsOilcardRepOrder oilcardRepOrder, YsOilcardOrder oilcardOrder,YsOilcardRechargeInfo oilcardRechargeInfo) throws Exception {
		//判断支付金额和套餐应付金额是否一致	
				String replenishOilcardOrderId=createReplenishOrder(oilcardOrder.getOilcardType()) ;
				oilcardRepOrder.setReplenishOrderId(replenishOilcardOrderId);			
				Member member=memberMapper.selectByThirdUserId(oilcardOrder.getMemberId());
				GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(member.getGroupId());
			
				 Map<String ,String>  result=this.finishSumitOilcardOrder(groupPayconfig, replenishOilcardOrderId, oilcardRechargeInfo, oilcardOrder);
				if("0000".equals(result.get("code"))){
					oilcardRepOrder.setRequestStatus(1);
					oilcardRechargeInfo.setAddedValueStatus("2");
					oilcardRechargeInfo.setRechargeStatus(1);//1、发送充值请求成功；
				}else if("9999".equals(result.get("code"))) {
					//当前时段 不能进行充值 ，提示错误
					return result;
				}else {
					oilcardRepOrder.setRequestStatus(2);
					oilcardRechargeInfo.setRechargeStatus(2);//2、发送充值请求失败；
				}
				oilcardRechargeInfo.setOilcardRechargeResultCord(result.get("code")+":"+result.get("msg"));
				oilcardRepOrder.setRechargeReqTime(new Date());
				
				oilcardRepOrderMapper.insert(oilcardRepOrder);
				oilcardRechargeInfo.setRechargeReqTime(new Date());//发送充值请求时间
				oilcardRechargeInfoMapper.updateByPrimaryKey(oilcardRechargeInfo);
				//重新检查订单状态
				finishCheckOilCardOrderStatus(oilcardOrder.getId());			
		   return result;
	}
	

	// 生成订单号
		private String createReplenishOrder(String oilcardType) {
			StringBuffer sBuffer = new StringBuffer();
			sBuffer.append(oilcardType);
			// 时间，到毫秒
			String dateToString =SysUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS");
			sBuffer.append(dateToString);
			// 生成四位随机数
			sBuffer.append(SysUtils.getFourRandom());
			sBuffer.append(BC_ORDER_FLAG);
			return sBuffer.toString();
		}

	@Override
	public List<YsOilcardRepOrder> selectByOilcardOrderId(BaseOilOrderInDTO listInDTO,Page page) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("page", page);
		map.put("orderId", listInDTO.getOrderId());
		int sumCount= this.oilcardRepOrderMapper.selectOilReChargeOrderByPageCounts(map);
		page.setTotalResult(sumCount);
		return this.oilcardRepOrderMapper.selectOilReChargeOrderByPage(map);
	}
	@Override
	public List<YsOilcardRepOrder> selectByOilcardReOrderId(Page page, Long reOrderId){
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("rechargeId", reOrderId);
	   Integer sumCount=	this.oilcardRepOrderMapper.selectOilReChargeOrderByPageCounts(map);
		page.setTotalResult(sumCount);
		if(sumCount<=0){
			return new ArrayList<YsOilcardRepOrder>();
		}
		map.put("limit", page.getShowCount());
		map.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		
	   return this.oilcardRepOrderMapper.selectOilReChargeOrderByPage(map);
		
	}
	@Override
	public List<YsOilcardRechargeInfo> findNeedChargeChargeInfo(String date) {
		
		return oilcardRechargeInfoMapper.findNeedChargeChargeInfo(date);
	}
	/**
	 * 
	 * @param tradeNo
	 * @param outTradeNo
	 * @return  TradeOffline 不为空表示 需要进行消费通知 为空表示 需要消费通知
	 */
	@Override
	public TradeOffline finishFlowsPayNotify(String tradeNo,String outTradeNo) throws Exception {
		/**
		 * 支付成功
		 */
		boolean needNotify=false;
		YsFlowChargeOrder payOrderFlowCharge=null;
		if(outTradeNo.length()<6){
			//这里 商户订单号 用了 id 			
			try {
				 payOrderFlowCharge= flowChargeMapper.selectByOrderId(Long.parseLong(outTradeNo));
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
			//System.out.println("添加测试。。。。。");
		}else{
			payOrderFlowCharge= flowChargeMapper.selectBySysOrderNum(outTradeNo);
			
		}
		
		if(tradeNo!=null&&!new Integer(1).equals(payOrderFlowCharge.getPayStatus())){	
			payOrderFlowCharge.setPayOrderNum(tradeNo);
			payOrderFlowCharge.setPayStatus(1);
			logger.info("----------------------流量购买会员总交易数1-----------------------------------");
			memberService.insertMemberTradeDataAsyn(payOrderFlowCharge.getYsMemberId(), payOrderFlowCharge.getPayAmount());
			logger.info("----------------------流量购买会员总交易数2-----------------------------------");
			needNotify=true;
		}	
		//完成通知
		String totalFee = String.format("%.2f",payOrderFlowCharge.getPayAmount()/100.0);	
		Response message=UserAuthApi.finishPayCall(payOrderFlowCharge.getOrderNumber(), tradeNo, totalFee,payOrderFlowCharge.getNotifyUrl());
		if(message.isStatus()){
			payOrderFlowCharge.setNotifyRespond(1);
		}
		TradeOffline tradeOffline=tradeOfflineMapper.selectByPrimaryKey(payOrderFlowCharge.getOrderId());
		//更新订单信息 
		tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
		tradeOffline.setMemo("支付成功");
		this.tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
		
//		try {
//			// 单笔交易分润计算 zsj
//			profitStatisService.saveOneOrderProfitCalculate(tradeOffline.getId());
//		} catch (Exception e) {
//			logger.info("单笔交易分润计算 出错了");
//		}
		int inNumber = this.flowChargeMapper.updateByPrimaryKey(payOrderFlowCharge);	
		if(needNotify){
			return tradeOffline;
		}else{
			return null;
		}
	}
	

	
	
	@Override
	public List<YsFlowChargeOrder> searchNotifyErrorflowCharge(int pageNumber, int pageSize) {
		
		
		Page page = new Page(pageNumber,pageSize);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("page", page);
		
		String tradeDate=SysUtils.formatDate(new Date(System.currentTimeMillis()-10*60*1000), "yyyy-MM-dd HH:mm:ss");
		String tradeMinDate=SysUtils.formatDate(new Date(System.currentTimeMillis()-48*60*60*1000), "yyyy-MM-dd HH:mm:ss");
		map.put("maxTradeDate", tradeDate);
		map.put("minTradeDate", tradeMinDate);
		return flowChargeMapper.searchNotifyErrorflowCharge(map);
		
	}

	@Override
	public Response bankPaySubmit(String groupCode, Long memberId, Long orderId,String ip, Map<String, Object> params) {
		Response request = new Response();
		Group businessBase = this.groupMapper.selectGroupByPayCode(groupCode);
		Member member = this.memberMapper.selectByPrimaryKey(memberId);
		if (businessBase == null || member == null || member.getGroupId().longValue() != businessBase.getId().longValue()) {
			/**
			 * 会员不是当前商户的
			 */
			return request.format(false, 0, "非法操作", null);
		}

		
		TradeOffline order=this.tradeOfflineMapper.selectByPrimaryKey(orderId);
		if(order==null || !order.getPayerId().equals(member.getId()) || !order.getGroupId().equals(businessBase.getId()) ){
			return request.format(false,0,"orderId 参数错误");
		}
		Long cardId=Long.valueOf(params.get("cardId").toString());
		MemberCard memberCard=this.memberCardMapper.selectByPrimaryKey(cardId);
		if(memberCard==null || !memberCard.getMemberId().equals(memberId)){
			return request.format(false,0,"非法操作");
		} 
		String thirdOrderNum=params.get("thirdOrderId").toString();
		String sysOrderNum=params.get("sysOrderNum").toString();
		String paySign=params.get("paySign").toString();
		String code=params.get("code").toString();
		
		if(Tools.isEmpty(sysOrderNum)||Tools.isEmpty(paySign)||Tools.isEmpty(thirdOrderNum)){
			
			return request.format(false, 0,"未填写资料信息", null);
		}
	
		
		if(memberCard.getCardStatus().equals(BizEnum.CardStatus.UnVerify.getType())){
			memberCard.setCardStatus(BizEnum.CardStatus.Verified.getType()); 
			memberCardMapper.updateByPrimaryKey(memberCard);
		}
		String orgOrderNum = UtilFun.createOrderNum();
		PayQuickPaymentRechargeSubmit qprs=PayQuickPaymentRechargeSubmit.initialize(groupCode, member.getVirtualCard(), sysOrderNum, null, code,
				thirdOrderNum, paySign, memberCard.getCardMobile(), memberCard.getCardNum(), orgOrderNum, ip);
	
		PayResult result=IPayAPI.userQuickPaymentRechargeSubmit(qprs);
		if(result==null || result.getVerificationStatus().byteValue()==Global.FALSE){ 
			return request.format(false,0,"充值失败,通信异常");
		}
		
		if(IPayAPI.Success.equals(result.getRespCode())){
			return request.format(true,2,result.getMsgTxt());
		}else{
			order.setTransactionStatus((byte)BizEnum.TransactionStatus.Failure.getType());
			order.setMemo(result.getMsgTxt());
			this.tradeOfflineMapper.updateByPrimaryKeySelective(order);
		}
		
		return request.format(false,0,result.getMsgTxt());
	}

	@Override
	public Response oilChargeOrderBankPay(String groupCode, Long memberId, Long cardId, Long goodsOrderId, Integer price,String ip) {
		Response request = new Response();
		Group businessBase = this.groupMapper.selectGroupByPayCode(groupCode);
		Member member = this.memberMapper.selectByPrimaryKey(memberId);
		if (businessBase == null || member == null || member.getGroupId().longValue() != businessBase.getId().longValue()) {
			/**
			 * 会员不是当前商户的
			 */
			return request.format(false, 0, "非法操作", null);
		}

		
		
		MemberCard memberCard=this.memberCardMapper.selectByPrimaryKey(cardId);
		if(memberCard==null || memberCard.getMemberId().longValue()!=memberId.longValue()){
			return request.format(false,0,"非法操作",null);
		} 
		 

		//查询出油卡订单 并且
		YsOilcardOrder oilcardOrder=oilcardOrderMapper.selectByPrimaryKey(goodsOrderId);
		if(!oilcardOrder.getMemberId().equals(member.getThirdUserId())){
			/**
			 * 订单不是当前会员的
			 */
			return request.format(false,0,"非法操作",null);
		}
		if(oilcardOrder.getPaymentStatus().byteValue()==2){
			/**
			 * 订单已经支付过了
			 */
			return request.format(true,1,"已经支付",null);
		}
		
		if(!oilcardOrder.getPaymentAmount().equals(price)){
			/**
			 * 订单金额不匹配
			 */
			return request.format(false,0,"订单金额不一至，支付失败",null);
		}
		
		
		String open=memberCard.getCardStatus().byteValue()== Global.TRUE ? "1" : "0";
		String cvnStr=null;
		if(StringUtils.isNotBlank(memberCard.getCardExpdate())&&StringUtils.isNotBlank(memberCard.getCardCvn())){
			cvnStr=memberCard.getCardCvn()+";"+memberCard.getCardExpdate();
		}	
		TradeOffline tradeOffline = null;
		String orgOrderNum = UtilFun.createOrderNum();
		if (oilcardOrder.getPayOrderId() == null) {
			tradeOffline = this.initializeOrder(BizEnum.TransactionType.Consumption, BizEnum.PaymentType.NetBankCardQuick, member, price, orgOrderNum,"OilRecharge");
		} else {
			tradeOffline = tradeOfflineMapper.selectByPrimaryKey(oilcardOrder.getPayOrderId());
			tradeOffline.setGmtModified(new Date());
			tradeOffline.setPayType( (byte)BizEnum.PaymentType.NetBankCardQuick.getType());
		}
		
		tradeOffline.setPayOrderid(oilcardOrder.getOilcardOrdernum());
		/**
		 * 防止订单号 重复，进行刷新
		 */
		reflashOilcardOrder(oilcardOrder,groupCode);
		String tranAmt = String.valueOf(price);	
		PayQuickPaymentPay payQuickPaymentPay=PayQuickPaymentPay.initialize(
				groupCode, 
  				member.getVirtualCard(), 
  				tranAmt,
  				memberCard.getBankIntegral(), 
  				"156",
  				memberCard.getIdName(),
  				memberCard.getCardNum(),
  				memberCard.getIdNo(), 
  				memberCard.getCardMobile(), 
  				"流量卡消费", 
  				DateUtil.fomatDate(tradeOffline.getGmtModified(),DateUtil.sdfTimes),
  				orgOrderNum,
  				open, 
  				oilcardOrder.getOilcardOrdernum(), 
  				cvnStr,ip);
		PayResult result=IPayAPI.userQuickPayment(payQuickPaymentPay);
		
		if(result==null || result.getVerificationStatus().byteValue()==Global.FALSE){
			
			return request.format(false,0,"交易失败,通信异常",null);
		}
		
		
		oilcardOrder.setPayOrderId(tradeOffline.getId());
		oilcardOrder.setPaymentType(PaymentType.NetBankCardQuick.getType());
		oilcardOrderMapper.updateByPrimaryKey(oilcardOrder);
		if(result==null || result.getVerificationStatus().byteValue()==Global.FALSE){
			
			return request.format(false,0,"充值失败,通信异常",null);
		}
		
		if(IPayAPI.Success.equals(result.getRespCode())){
			/**
			 * 快捷支付消费
			 */  
			this.tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
			Map<String,Object> data=new HashMap<String,Object>(); 
			data.put("thirdOrderId", result.getThirdOrderId());
			data.put("sysOrderNum", result.getSysOrderNum());
			data.put("paySign", result.getPaySign());
			data.put("mobile", memberCard.getCardMobile().substring(memberCard.getCardMobile().length()-4));
			data.put("cardId", cardId);
			data.put("orderId",tradeOffline.getId());
			
			return request.format(true,1,null,data);
		}else{
			tradeOffline.setMemo(result.getMsgTxt());
			tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Failure.getType());
			this.tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
		}	
		return request.format(false,0,result.getMsgTxt(),null);
	}

	@Override
	public Response flowsOrderPay(String orderNum, String notifyUrl, Integer goodsOrderPrice, String payPwd, Long memberId, String groupId) throws Exception {
		Response request = new Response();
		Group businessBase = this.groupMapper.selectGroupByPayCode(groupId);
		Member member = this.memberMapper.selectByPrimaryKey(memberId);
		if (businessBase == null || member == null || member.getGroupId().longValue() != businessBase.getId().longValue()) {
			/**
			 * 会员不是当前商户的
			 */
			return request.format(false, 0, "非法操作", null);
		}

		String groupTag=groupId.substring(groupId.length()-9);
		YsFlowChargeOrder payOrderFlowCharge =this.flowChargeMapper.selectByOrderNum(orderNum);
		TradeOffline order=null;
		String orgOrderNum = UtilFun.createOrderNum();		
		if(payOrderFlowCharge==null){
			order=this.initializeOrder(BizEnum.TransactionType.Consumption,BizEnum.PaymentType.Wallet, member,goodsOrderPrice, orgOrderNum,"FlowRecharge");
			//查询这个订单的支付记录
			payOrderFlowCharge=new YsFlowChargeOrder();
			payOrderFlowCharge.setNotifyRespond(0);
			payOrderFlowCharge.setNotifyUrl(notifyUrl);
			payOrderFlowCharge.setOrderId(order.getId());
			payOrderFlowCharge.setOrderNumber(orderNum);
			payOrderFlowCharge.setPayAmount(goodsOrderPrice);
			payOrderFlowCharge.setPayDate(new Date()); 
			payOrderFlowCharge.setPayStatus(0);
			payOrderFlowCharge.setPayType(PaymentType.Wallet.getType());
			String defaultFlowId=String.format("LF%s%s",groupTag ,String.format("%010d",order.getId())); 
			payOrderFlowCharge.setSysOrderNumber(defaultFlowId);
			payOrderFlowCharge.setNotifyRespond(0);
			payOrderFlowCharge.setYsMemberId(member.getThirdUserId());
			int inNumber=this.flowChargeMapper.insert(payOrderFlowCharge);
			if(inNumber==0){
				return request.format(false,0,"系统异常，支付失败");
			}
		}else{
			
			order=this.tradeOfflineMapper.selectByPrimaryKey(payOrderFlowCharge.getOrderId());
			order.setGmtModified(new Date());
			order.setPayType((byte)BizEnum.PaymentType.Wallet.getType());
			orgOrderNum=order.getPayOrderid();
		}	
		
		if(payOrderFlowCharge.getPayStatus().intValue()==1){
			/**
			 * 订单已经支付过了
			 */
			return request.format(true,1,"订单已支付");
		}
		//防止订单号重复
		//去更新一下商品订单的系统订单号
		
		String defaultFlowId=String.format("LF%s%s",groupTag ,String.format("%010d", order.getId())); 
		String newSysOrderNumber = reflashOrderNum(defaultFlowId, payOrderFlowCharge.getSysOrderNumber(),null);
	    order.setPayBakOrderid(newSysOrderNumber);
		payOrderFlowCharge.setSysOrderNumber(newSysOrderNumber);
		payOrderFlowCharge.setPayDate(new Date());		
		payOrderFlowCharge.setNotifyUrl(notifyUrl);
		payOrderFlowCharge.setPayAmount(goodsOrderPrice);
		payOrderFlowCharge.setPayType((int) PaymentType.Wallet.getType());
		int inNumber = this.flowChargeMapper.updateByPrimaryKey(payOrderFlowCharge);
		if (inNumber == 0) {
			return request.format(false, 0, "系统异常，支付失败");
		} 
		String tranAmt = String.valueOf(goodsOrderPrice); 
		 String SysTraceNum=DateUtil.getSdfTimes()+Tools.getRandomNum(4);
		 PayResult result =walletService.updatePayConsumption(member.getVirtualCard(), groupId, member.getUserId(),
				 goodsOrderPrice, SysTraceNum, payPwd,null,orgOrderNum);
				if (!result.getRespCode().equals("0000")) {
					throw new ApplicationException(Rescode.FAIL, result.getMsgTxt());
				}
		
		if(IPayAPI.Success.equals(result.getRespCode())){
			/**
			 * 支付成功
			 */
			order.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
			order.setMemo(result.getMsgTxt());
			this.tradeOfflineMapper.updateByPrimaryKeySelective(order);
			payOrderFlowCharge.setPayOrderNum(result.getOrderId());
			payOrderFlowCharge.setPayStatus(1);
			inNumber = this.flowChargeMapper.updateByPrimaryKey(payOrderFlowCharge);
			finishFlowsPayNotify(payOrderFlowCharge.getPayOrderNum(), payOrderFlowCharge.getSysOrderNumber());
			try {
				// 会员交易数据异步 zsj
				memberService.insertMemberTradeDataAsyn(member.getId(), Integer.valueOf(tranAmt));
			} catch (Exception e) {
				logger.info("插入会员交易数据异步");
			}
			return request.format(true,1,"交易成功",null,orgOrderNum);
		} else{
			order.setTransactionStatus((byte)BizEnum.TransactionStatus.Failure.getType());
			order.setMemo(result.getMsgTxt());
			this.tradeOfflineMapper.updateByPrimaryKeySelective(order);
		}
		return request.format(false,0,IPayAPI.getErrorText(result, result.getMsgTxt()));
	}
	@Override
	public Response flowsOrderWxPay(String orderNum, Integer goodsOrderPrice, Long memberId, String groupId, String ip, String notifyUrl) {
		Response request = new Response();
		Group businessBase = this.groupMapper.selectGroupByPayCode(groupId);
		Member member = this.memberMapper.selectByPrimaryKey(memberId);
		if (businessBase == null || member == null || member.getGroupId().longValue() != businessBase.getId().longValue()) {
			/**
			 * 会员不是当前商户的
			 */
			return request.format(false, 0, "非法操作", null);
		}

		String groupTag=groupId.substring(groupId.length()-9);
		YsFlowChargeOrder payOrderFlowCharge =this.flowChargeMapper.selectByOrderNum(orderNum);
		
		TradeOffline order=null;
		String orgOrderNum = UtilFun.createOrderNum();		
		if(payOrderFlowCharge==null){
			order=this.initializeOrder(BizEnum.TransactionType.Consumption,BizEnum.PaymentType.WebChat, member,goodsOrderPrice, orgOrderNum,"FlowRecharge");
			//查询这个订单的支付记录
			payOrderFlowCharge=new YsFlowChargeOrder();
			payOrderFlowCharge.setNotifyRespond(0);
			payOrderFlowCharge.setNotifyUrl(notifyUrl);
			payOrderFlowCharge.setOrderId(order.getId());
			payOrderFlowCharge.setOrderNumber(orderNum);
			payOrderFlowCharge.setPayAmount(goodsOrderPrice);
			payOrderFlowCharge.setPayDate(new Date()); 
			payOrderFlowCharge.setPayStatus(0);
			payOrderFlowCharge.setPayType((int)PaymentType.WebChat.getType());
			String defaultFlowId=String.format("LF%s%s",groupTag ,String.format("%010d",order.getId())); 
			payOrderFlowCharge.setSysOrderNumber(defaultFlowId);
			payOrderFlowCharge.setNotifyRespond(0);
			payOrderFlowCharge.setYsMemberId(member.getThirdUserId());
			int inNumber=this.flowChargeMapper.insert(payOrderFlowCharge);
			if(inNumber==0){
				return request.format(false,0,"系统异常，支付失败");
			}
		}else{
			order=this.tradeOfflineMapper.selectByPrimaryKey(payOrderFlowCharge.getOrderId());
			order.setGmtModified(new Date());
			order.setPayType((byte)BizEnum.PaymentType.WebChat.getType());
		}		
		if(payOrderFlowCharge.getPayStatus().intValue()==1){
			/**
			 * 订单已经支付过了
			 */
			return request.format(true,1,"订单支付",null);
		}
		
		//防止订单号重复
		//去更新一下商品订单的系统订单号
 //		String defaultFlowId=String.format("LF%s%s",groupTag ,String.format("%010d",order.getOrderId())); 
//		String newCode = reflashOrderNum(defaultFlowId, payOrderFlowCharge.getSysOrderNumber());
//		payOrderFlowCharge.setSysOrderNumber(newCode);
		payOrderFlowCharge.setPayDate(new Date());		
		payOrderFlowCharge.setNotifyUrl(notifyUrl);
		payOrderFlowCharge.setPayAmount(goodsOrderPrice);
		payOrderFlowCharge.setPayType((int) PaymentType.WebChat.getType());
		int inNumber = this.flowChargeMapper.updateByPrimaryKey(payOrderFlowCharge);
		if (inNumber == 0) {
			return request.format(false, 0, "系统异常，支付失败");
		} 	
		
		
		try {
			WxPayUnifiedOrderResult unifiedorderResult=wxpayUnifiedOrder("云流-流量商品购买",payOrderFlowCharge.getSysOrderNumber(),goodsOrderPrice,ip,Global.HOME_URL+WXFLOWSPAY_NOTIFY_URL,businessBase.getId());		
			if ("SUCCESS".equals(unifiedorderResult.getReturnCode())){
				 if("SUCCESS".equals(unifiedorderResult.getResultCode())){
					 Map<String ,Object> result=new HashMap<String ,Object>();
					 result.put("appid", unifiedorderResult.getAppid());
					 result.put("mch_id", unifiedorderResult.getMchId());
					 result.put("nonce_str", unifiedorderResult.getNonceStr());
					 result.put("sign", unifiedorderResult.getSign());
					 result.put("prepay_id", unifiedorderResult.getPrepayId());
					 result.put("trade_type", unifiedorderResult.getTradeType());
					 return request.format(true, 1, "下单成功", result);
				 }else{
					 return request.format(false,0,unifiedorderResult.getErrCode()+":"+unifiedorderResult.getErrCodeDes(),null);
				 }
			}else{
				 return request.format(false,0,unifiedorderResult.getReturnMsg(),null);
			}
				
		} catch (Exception e) {
			e.printStackTrace();
			 return request.format(false,0,"微信支付配置错误",null);
		} 	
		
	
	}
	
	@Override
	public Response flowsOrderAliPay(String orderNum, Integer goodsOrderPrice, Long memberId, String groupId, String notifyUrl) {
		Response request = new Response();
		Group businessBase = this.groupMapper.selectGroupByPayCode(groupId);
		Member member = this.memberMapper.selectByPrimaryKey(memberId);
		if (businessBase == null || member == null || member.getGroupId().longValue() != businessBase.getId().longValue()) {
			/**
			 * 会员不是当前商户的
			 */
			return request.format(false, 0, "非法操作", null);
		}

		
		String groupTag=groupId.substring(groupId.length()-9);
		YsFlowChargeOrder payOrderFlowCharge =this.flowChargeMapper.selectByOrderNum(orderNum);
		TradeOffline order=null;
		String orgOrderNum = UtilFun.createOrderNum();		
		if(payOrderFlowCharge==null){
			order=this.initializeOrder(BizEnum.TransactionType.Consumption,BizEnum.PaymentType.AliPay, member,goodsOrderPrice, orgOrderNum,"FlowRecharge");
			//查询这个订单的支付记录
			payOrderFlowCharge=new YsFlowChargeOrder();
			payOrderFlowCharge.setNotifyRespond(0);
			payOrderFlowCharge.setNotifyUrl(notifyUrl);
			payOrderFlowCharge.setOrderId(order.getId());
			payOrderFlowCharge.setOrderNumber(orderNum);
			payOrderFlowCharge.setPayAmount(goodsOrderPrice);
			payOrderFlowCharge.setPayDate(new Date()); 
			payOrderFlowCharge.setPayStatus(0);
			payOrderFlowCharge.setPayType((int)PaymentType.AliPay.getType());
			String defaultFlowId=String.format("LF%s%s",groupTag ,String.format("%010d",order.getId())); 
			payOrderFlowCharge.setSysOrderNumber(defaultFlowId);
			payOrderFlowCharge.setNotifyRespond(0);
			payOrderFlowCharge.setYsMemberId(member.getThirdUserId());
			int inNumber=this.flowChargeMapper.insert(payOrderFlowCharge);
			if(inNumber==0){
				return request.format(false,0,"系统异常，支付失败");
			}
		}else{
			order=this.tradeOfflineMapper.selectByPrimaryKey(payOrderFlowCharge.getOrderId());
			order.setGmtModified(new Date());
			order.setPayType((byte)BizEnum.PaymentType.AliPay.getType());
		}		
		if(payOrderFlowCharge.getPayStatus().intValue()==1){
			/**
			 * 订单已经支付过了
			 */
			return request.format(true,1,"订单支付",null);
		}
		
		//防止订单号重复
		//去更新一下商品订单的系统订单号

		payOrderFlowCharge.setPayDate(new Date());		
		payOrderFlowCharge.setNotifyUrl(notifyUrl);
		payOrderFlowCharge.setPayAmount(goodsOrderPrice);
		payOrderFlowCharge.setPayType( PaymentType.AliPay.getType());
		int inNumber = this.flowChargeMapper.updateByPrimaryKey(payOrderFlowCharge);
		if (inNumber == 0) {
			return request.format(false, 0, "系统异常，支付失败");
		} 	
		Map<String, Object> result = new HashMap<String, Object>();
		String payNotifyUrl=Global.HOME_URL+FLOWSALIPAY_NOTIFY_URL;
		result.put("notifyUrl", payNotifyUrl);
		result.put("orderId", order.getId());
		String tranAmt = String.valueOf(goodsOrderPrice);
		result.put("tranAmt", tranAmt);
		result.put("merchantOrderNum", payOrderFlowCharge.getSysOrderNumber());
		return request.format(true, 1, "下单成功",result );
		
	}
	@Override
	public Response flowsOrderBankPay(String groupCode, Long memberId, Long cardId, String orderNum, Integer goodsOrderPrice, String notifyUrl,String ip) {
		Response request = new Response();
		Group businessBase = this.groupMapper.selectGroupByPayCode(groupCode);
		Member member = this.memberMapper.selectByPrimaryKey(memberId);
		if (businessBase == null || member == null || member.getGroupId().longValue() != businessBase.getId().longValue()) {
			/**
			 * 会员不是当前商户的
			 */
			return request.format(false, 0, "非法操作", null);
		}

		
		
		MemberCard memberCard=this.memberCardMapper.selectByPrimaryKey(cardId);
		if(memberCard==null || memberCard.getMemberId().longValue()!=memberId.longValue()){
			return request.format(false,0,"非法操作",null);
		} 
		
		YsFlowChargeOrder payOrderFlowCharge =this.flowChargeMapper.selectByOrderNum(orderNum);
		String groupTag=groupCode.substring(groupCode.length()-9);
		TradeOffline tradeOffline=null;
		String orgOrderNum = UtilFun.createOrderNum();		
		if(payOrderFlowCharge==null){
			tradeOffline=this.initializeOrder(BizEnum.TransactionType.Consumption,BizEnum.PaymentType.NetBankCardQuick, member,goodsOrderPrice, orgOrderNum,"FlowRecharge");
			//查询这个订单的支付记录
			payOrderFlowCharge=new YsFlowChargeOrder();
			payOrderFlowCharge.setNotifyRespond(0);
			payOrderFlowCharge.setNotifyUrl(notifyUrl);
			payOrderFlowCharge.setOrderId(tradeOffline.getId());
			payOrderFlowCharge.setOrderNumber(orderNum);
			payOrderFlowCharge.setPayAmount(goodsOrderPrice);
			payOrderFlowCharge.setPayDate(new Date()); 
			payOrderFlowCharge.setPayStatus(0);
			payOrderFlowCharge.setPayType((int)PaymentType.NetBankCardQuick.getType());
			String defaultFlowId=String.format("LF%s%s",groupTag ,String.format("%010d",tradeOffline.getId())); 
			payOrderFlowCharge.setSysOrderNumber(defaultFlowId);
			payOrderFlowCharge.setNotifyRespond(0);
			payOrderFlowCharge.setYsMemberId(member.getThirdUserId());
			int inNumber=this.flowChargeMapper.insert(payOrderFlowCharge);
			if(inNumber==0){
				return request.format(false,0,"系统异常，支付失败",null);
			}
		}else{
			tradeOffline=this.tradeOfflineMapper.selectByPrimaryKey(payOrderFlowCharge.getOrderId());
			tradeOffline.setGmtModified(new Date());
			tradeOffline.setPayType((byte)BizEnum.PaymentType.NetBankCardQuick.getType());
		}		
		if(payOrderFlowCharge.getPayStatus().intValue()==1){
			/**
			 * 订单已经支付过了
			 */
			return request.format(true,1,"订单支付",null);
		}		
		
		
		String open=memberCard.getCardStatus().byteValue()== Global.TRUE ? "1" : "0";
		String cvnStr=null;
		if(StringUtils.isNotBlank(memberCard.getCardExpdate())&&StringUtils.isNotBlank(memberCard.getCardCvn())){
			cvnStr=memberCard.getCardCvn()+";"+memberCard.getCardExpdate();
		}	
		//防止订单号重复
		//去更新一下商品订单的系统订单号
		String defaultFlowId=String.format("LF%s%s",groupTag ,String.format("%010d",tradeOffline.getId())); 
//		payOrderFlowCharge.setSysOrderNumber(defaultFlowId);
		String newSysOrderNumber = reflashOrderNum(defaultFlowId, payOrderFlowCharge.getSysOrderNumber(),null);
		tradeOffline.setPayBakOrderid(newSysOrderNumber);
		payOrderFlowCharge.setSysOrderNumber(newSysOrderNumber);
		payOrderFlowCharge.setPayDate(new Date());		
		payOrderFlowCharge.setNotifyUrl(notifyUrl);
		payOrderFlowCharge.setPayAmount(goodsOrderPrice);
		payOrderFlowCharge.setPayType( PaymentType.NetBankCardQuick.getType());
		int inNumber = this.flowChargeMapper.updateByPrimaryKey(payOrderFlowCharge);
		if (inNumber == 0) {
			return request.format(false, 0, "系统异常，支付失败" ,null);
		} 	
		
		String tranAmt = String.valueOf(goodsOrderPrice);	
		PayQuickPaymentPay payQuickPaymentPay=PayQuickPaymentPay.initialize(
				groupCode, 
  				member.getVirtualCard(), 
  				tranAmt,
  				memberCard.getBankIntegral(), 
  				"156",
  				memberCard.getIdName(),
  				memberCard.getCardNum(),
  				memberCard.getIdNo(), 
  				memberCard.getCardMobile(), 
  				"流量卡消费", 
  				DateUtil.fomatDate(tradeOffline.getGmtModified(),DateUtil.sdfTimes),
  				orgOrderNum,
  				open, 
  				payOrderFlowCharge.getSysOrderNumber(), 
  				cvnStr,ip);
		PayResult result=IPayAPI.userQuickPayment(payQuickPaymentPay);
		
		if(result==null || result.getVerificationStatus().byteValue()==Global.FALSE){
			
			return request.format(false,0,"交易失败,通信异常",null);
		}
		
		if(IPayAPI.Success.equals(result.getRespCode())){
			/**
			 * 快捷支付消费
			 */  
			Map<String,Object> data=new HashMap<String,Object>(); 
			data.put("thirdOrderId", result.getThirdOrderId());
			data.put("sysOrderNum", result.getSysOrderNum());
			data.put("paySign", result.getPaySign());
			data.put("mobile", memberCard.getCardMobile().substring(memberCard.getCardMobile().length()-4));
			data.put("cardId", cardId);
			data.put("orderId",tradeOffline.getId());
			this.tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
			return request.format(true,1,null,data);
		}else{
			tradeOffline.setMemo(result.getMsgTxt());
			tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Failure.getType());
			this.tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
		}	
		return request.format(false,0,result.getMsgTxt(),null);
	}

	/**
	 * 更新一下商品订单号 ,从0-Z补位
	 * @param baseOrderCode
	 */
	private String reflashOrderNum(String baseOrderCode, String currOrderCode,String prefix) {
		String newCode=null;
		if(baseOrderCode.equals(currOrderCode)){
	    	//还没有更新过
	    	 newCode=currOrderCode+"1";
	    	if(org.apache.commons.lang.StringUtils.isNotBlank(prefix)){
	    		newCode= prefix+newCode;
	    	}
	    	
	    }else{
	    	//表示曾经补位
	    	char last=currOrderCode.charAt(currOrderCode.length()-1);
	    	if(last=='9'){
	    		last='A';
	    	}else{
	    		last=(char) (last+1);
	    	}
	    	
	    	newCode= currOrderCode.substring(0, currOrderCode.length()-1)+last;	    	
	    }
		System.out.println("reflashOrderNum:::baseOrderCode:"+baseOrderCode+";currOrderCode::"+currOrderCode+":newCode:"+newCode);
		return newCode;
	}
	
	/**
	 *  微信 支付统一下单
	 * @return
	 */
	/**
	 * @param goodInfo
	 * @param sysOrderNumber
	 * @param tranAmt
	 * @param ip
	 * @param notifyUrl
	 * @param groupId
	 * @return
	 * @throws WxErrorException 
	 */
	private WxPayUnifiedOrderResult wxpayUnifiedOrder(String goodInfo, String sysOrderNumber, Integer tranAmt, String ip, String notifyUrl,Long groupId) throws WxErrorException {
		
		
		GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(groupId);
		
		
		WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
		
		String nonce_str = RandomStringUtils.randomAlphanumeric(28);
		orderRequest.setAppid(groupPayconfig.getWxAppid());
		orderRequest.setMchId(groupPayconfig.getWxMerchantno());
		
		orderRequest.setNonceStr(nonce_str);
		orderRequest.setDeviceInfo("WEB");
		orderRequest.setBody(goodInfo);
		orderRequest.setOutTradeNo(sysOrderNumber);
		orderRequest.setTotalFee(tranAmt);// 单位分
		orderRequest.setSpbillCreateIp(ip);// IP
		orderRequest.setNotifyURL(notifyUrl);
		orderRequest.setTradeType("APP");// JSAPI，NATIVE，APP，WAP
	
		WxPayConfig wxPayConfig=new WxPayConfig();
		wxPayConfig.setAppId(groupPayconfig.getWxAppid()); 
		wxPayConfig.setMchId(groupPayconfig.getWxMerchantno()); 
		wxPayConfig.setMchKey(groupPayconfig.getWxPayKey());
		
		
		 WxPayService wxPayService=new WxPayServiceImpl();
		 wxPayService.setConfig(wxPayConfig);
		 WxPayUnifiedOrderResult	unifiedorderResult = wxPayService.unifiedOrder(orderRequest);
		 
		 
		return unifiedorderResult;
	}

	@Override
	public boolean verfyOilCardAliPay(HashMap<String, String> params, String oilcardOrderNum)
	{
		YsOilcardOrder order = findOilOrderInfo(oilcardOrderNum);
		if(order==null){
			return false;
		}
		Member member=memberMapper.selectByThirdUserId(order.getMemberId());
		GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(member.getGroupId());
		try {
			return  AlipaySignature.rsaCheckV1(params, groupPayconfig.getAliPublicKey(), Const.CHARTSET_UTF8, Const.ALIPAY_DES_TYPE_RSA);
		} catch (AlipayApiException e) {
			
			e.printStackTrace();
			return false;
		}
	}

	
	
	@Override
	public boolean verfyFlowChargeAliPay(HashMap<String, String> params, String out_trade_no) {
		YsFlowChargeOrder flowChargeOrder=null;
		if(out_trade_no.length()<6){
			//这里 商户订单号 用了 id 不是
			 try {
				flowChargeOrder= flowChargeMapper.selectByPrimaryKey(Long.parseLong(out_trade_no));
			} catch (NumberFormatException e) {
				e.printStackTrace();
				return false;
				
			}
				
		}else{
			 flowChargeOrder= flowChargeMapper.selectBySysOrderNum(out_trade_no);
			
		}
		if(flowChargeOrder==null){
			return false;
		}
		
		Member member=memberMapper.selectByThirdUserId(flowChargeOrder.getYsMemberId());
		GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(member.getGroupId());
		
		try {
			return  AlipaySignature.rsaCheckV1(params, groupPayconfig.getAliPublicKey(), Const.CHARTSET_UTF8, Const.ALIPAY_DES_TYPE_RSA);
		} catch (AlipayApiException e) {
			
			e.printStackTrace();
			return false;
		}
		
	}

	//油卡充值月任务
	public int saveOilcardChargeMonthTask(Date statisDate) throws Exception{
		int result =0;

		String currentDate=DateUtil.fomatDate(statisDate,DateUtil.sdfDay);
		List<YsOilcardRechargeInfo> rechargeInfos= findNeedChargeChargeInfo(currentDate);
		for(YsOilcardRechargeInfo chargeInfo:rechargeInfos){
			try {
				finishOilcardRechargeInfoRecharge(chargeInfo);
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				Thread.sleep(10*1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		return result;
	}
	/**
	 * 校验MD5参数值
	 * •appId=xxx&userId=xxx&outTradeNo=xxx&orderSum=xxx&
	 * gasAccount=xxx&gasOwner=xxx&gasType=xxx&phone=xxx&orderId=xxx&createTime=xxx
	 * &status=xxxappKey的MD5值。注意status为status的值拼上appKey的值。appKey值从商户平台获取。
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean checkOilChargeSign(HttpServletRequest request) {
		
		
			String appId = new String(request.getParameter("appId"));
			String userId = new String(request.getParameter("userId"));
			String outTradeNo = new String(request.getParameter("outTradeNo"));
			String orderSum = new String(request.getParameter("orderSum"));
			String gasAccount = new String(request.getParameter("gasAccount"));
			String gasOwner = new String(request.getParameter("gasOwner"));
			String gasType = new String(request.getParameter("gasType"));
			String phone = new String(request.getParameter("phone"));
			String orderId = new String(request.getParameter("orderId"));
			String createTime = new String(request.getParameter("createTime"));
			int status = Integer.valueOf(request.getParameter("status"));
			String sign = new String(request.getParameter("sign"));
			
			
			String bcOrderFlag = outTradeNo.substring(outTradeNo.length() - 2);
			YsOilcardRechargeInfo oilcardRechargeInfo=null;
			
			if (!BC_ORDER_FLAG.equals(bcOrderFlag)) {
				oilcardRechargeInfo = oilcardRechargeInfoMapper.selectByRechargeOrderNum(outTradeNo);

			} else {
				YsOilcardRepOrder ocrOrder= oilcardRepOrderMapper.selectByReplenishOrderId(outTradeNo);
				if (ocrOrder == null) {
					logger.info("service of pay the order number " + outTradeNo + " is not found");
					return false;
				}
				 oilcardRechargeInfo = oilcardRechargeInfoMapper.selectByPrimaryKey(ocrOrder.getOilcardRechargeId());
			}
			if (oilcardRechargeInfo == null) {
				logger.info("service of pay the order number " + outTradeNo + " is not found");
				return false;
			}
			Long oilcardOrderId=oilcardRechargeInfo.getOilcardOrderId();
			 YsOilcardOrder oilcardOrder=oilcardOrderMapper.selectByPrimaryKey(oilcardOrderId);	
			Member member=memberMapper.selectByThirdUserId(oilcardOrder.getMemberId());
			GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(member.getGroupId());
			
			String oilCardAgentAppKey=groupPayconfig.getAgentAppkey();
			
			StringBuffer sb = new StringBuffer("appId=");
			sb.append(appId);
			sb.append("&userId=").append(userId).append("&outTradeNo=").append(outTradeNo);
			sb.append("&orderSum=").append(orderSum).append("&gasAccount=").append(gasAccount);
			sb.append("&gasOwner=").append(gasOwner).append("&gasType=").append(gasType);
			sb.append("&phone=").append(phone).append("&orderId=").append(orderId);
			sb.append("&createTime=").append(createTime).append("&status=").append(status).append(oilCardAgentAppKey);
			String md5Sign = UtilFun.stringMD5(sb.toString());
			logger.info("油卡充值回调信息：---------》"+sb.toString());
			logger.info("sign--------------->"+sign);
			logger.info("md5Sign---------------->"+md5Sign);
			if(!md5Sign.equalsIgnoreCase(sign)){
				return false;
			}
			return true;

		}
	/**
	 * 校验MD5参数值
	 * •appId=xxx&userId=xxx&outTradeNo=xxx&orderSum=xxx&
	 * gasAccount=xxx&gasOwner=xxx&gasType=xxx&phone=xxx&orderId=xxx&createTime=xxx
	 * &status=xxxappKey的MD5值。注意status为status的值拼上appKey的值。appKey值从商户平台获取。
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean checkOilChargeSign2(HttpServletRequest request) {
		
		
			String bizId =request.getParameter("bizId");
			String downstreamSerialno = request.getParameter("downstreamSerialno");
			String ejId = request.getParameter("ejId");
			String status = request.getParameter("status");
			String userId  = request.getParameter("userId");
			
			String sign = request.getParameter("sign");
			
			if(downstreamSerialno==null||bizId==null||ejId==null||status==null||userId==null||sign==null){
				return false;
			}
			
			String bcOrderFlag = downstreamSerialno.substring(downstreamSerialno.length() - 2);
			YsOilcardRechargeInfo oilcardRechargeInfo=null;
			
			if (!BC_ORDER_FLAG.equals(bcOrderFlag)) {
				oilcardRechargeInfo = oilcardRechargeInfoMapper.selectByRechargeOrderNum(downstreamSerialno);

			} else {
				YsOilcardRepOrder ocrOrder= oilcardRepOrderMapper.selectByReplenishOrderId(downstreamSerialno);
				if (ocrOrder == null) {
					logger.info("service of pay the order number " + downstreamSerialno + " is not found");
					return false;
				}
				 oilcardRechargeInfo = oilcardRechargeInfoMapper.selectByPrimaryKey(ocrOrder.getOilcardRechargeId());
			}
			if (oilcardRechargeInfo == null) {
				logger.info("service of pay the order number " + downstreamSerialno + " is not found");
				return false;
			}
			Long oilcardOrderId=oilcardRechargeInfo.getOilcardOrderId();
			 YsOilcardOrder oilcardOrder=oilcardOrderMapper.selectByPrimaryKey(oilcardOrderId);	
			Member member=memberMapper.selectByThirdUserId(oilcardOrder.getMemberId());
			GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(member.getGroupId());
			
			String oilCardAgentAppKey=groupPayconfig.getAgentAppkey();
			
			StringBuffer sb = new StringBuffer();
			sb.append(bizId)
			.append(downstreamSerialno)
			.append(ejId)
			.append(status)
			.append(userId)
	        .append(oilCardAgentAppKey);
			String md5Sign = UtilFun.stringMD5(sb.toString());
			logger.info("油卡充值回调信息：---------》"+sb.toString());
			logger.info("sign--------------->"+sign);
			logger.info("md5Sign---------------->"+md5Sign);
			if(!md5Sign.equalsIgnoreCase(sign)){
				return false;
			}
			return true;

		}
	

	public static void main(String[] args) {
		String groupTag="333";
		String defaultFlowId=String.format("LF%s%s",groupTag ,String.format("%010d",11l)); 
	   System.out.println(defaultFlowId);
	}

	@Override
	public BaseOutDTO finishFlowsPayNotify(Long orderId) {
		BaseOutDTO baseOutDTO=new BaseOutDTO();
		YsFlowChargeOrder payOrderFlowCharge =flowChargeMapper.selectByPrimaryKey(orderId);
		String totalFee = String.format("%.2f",payOrderFlowCharge.getPayAmount()/100.0);	
		String orderNumber=payOrderFlowCharge.getOrderNumber();
		String tradeNo=payOrderFlowCharge.getPayOrderNum();
		Response message=UserAuthApi.finishPayCall(orderNumber, tradeNo, totalFee,payOrderFlowCharge.getNotifyUrl());
		if(message.isStatus()){
			payOrderFlowCharge.setNotifyRespond(1);
			 flowChargeMapper.updateByPrimaryKey(payOrderFlowCharge);
			 baseOutDTO.setErrorCode(Rescode.SUCCESS);
		}else{
			baseOutDTO.setErrorCode("OS34", "通知失败");
		}
		return baseOutDTO;
	}

	@Override
	public List<FlowChargeOrderBean> listFlowsCharge(FlowOrderListInDTO listInDTO, Page page) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("businessId", listInDTO.getGroupId());
		map.put("orderNumber", listInDTO.getOrderNumber());
		map.put("payOrderNum",  listInDTO.getPayOrderNum());
		map.put("sysOrderNumber",  listInDTO.getSysOrderNumber());
		
        int sumCount = flowChargeMapper.selectFlowOrderCounts(map);
		
		page.setTotalResult(sumCount);
		if(sumCount<=0){
			return new ArrayList<FlowChargeOrderBean>();
		}
		map.put("limit", page.getShowCount());
		map.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		return this.flowChargeMapper.selectFlowOrderList(map);
	
	}

	@Override
	public String finishCancelOilCharge(CancelOilChargeInDTO canceOilDTO) {
		String oilchargeOrderIds=canceOilDTO.getOilchargeOrderIds();
		String[] oilchargeOrderIdArr=oilchargeOrderIds.split(",");
		ArrayList<YsOilcardRechargeInfo> chargeInfos=new ArrayList<YsOilcardRechargeInfo>();
		for(String orderId : oilchargeOrderIdArr){
			YsOilcardRechargeInfo ysOilcardRechargeInfo=oilcardRechargeInfoMapper.selectByPrimaryKey(SysUtils.Object2Long(orderId));
			if(ysOilcardRechargeInfo==null||!canceOilDTO.getOilOrderId().equals(ysOilcardRechargeInfo.getOilcardOrderId())||ysOilcardRechargeInfo.getRechargeStatus().intValue()!=0){
				return "记录ID"+orderId+"，数据不对，不能进行取消";
			}else{
				chargeInfos.add(ysOilcardRechargeInfo);
			}
		}
		
		for(YsOilcardRechargeInfo ysOilcardRechargeInfo:chargeInfos){
			ysOilcardRechargeInfo.setRechargeStatus(-1);//表示已取消
			oilcardRechargeInfoMapper.updateByPrimaryKey(ysOilcardRechargeInfo);
		}
		//
		finishCheckOilCardOrderStatus(canceOilDTO.getOilOrderId());
		return null;
	}

	@Override
	public void saveFlowChargeDayStatis(Date statisDate) {
		String statisDateStr=DateUtil.fomatDate(statisDate, DateUtil.sdfDay);
		
			List<Long> groupIds=flowChargeMapper.findGroupIdInflowChargeOrder(statisDateStr);
		for(Long groupId:groupIds){
			StatisFlowCharge statisFlowCharge =statisFlowChargeMapper.selectByStatisDate(statisDateStr,groupId);
			
		if(statisFlowCharge==null){
			statisFlowCharge=new StatisFlowCharge();
			statisFlowCharge.setDay(statisDateStr);
			statisFlowCharge.setGmtCreate(new Date());
			statisFlowCharge.setGmtModified(new Date());
			statisFlowCharge.setQrcodePayAmount(0);
			statisFlowCharge.setQrcodePayCount(0);
			statisFlowCharge.setGroupId(groupId);
			statisFlowCharge.setWalletPayAmount(0);
			statisFlowCharge.setWalletPayCount(0);
		
			statisFlowCharge.setWeixinPayAmount(0);
			statisFlowCharge.setWeixinPayCount(0);
			statisFlowCharge.setAliPayAmount(0);
			statisFlowCharge.setAliPayCount(0);
			statisFlowCharge.setBankPayAmount(0);
			statisFlowCharge.setBankPayCount(0);
		
	
		}
		List<Map<String,Object>> result=flowChargeMapper.selectStaticGroupByPayType(statisDateStr,groupId);
		
		for(Map<String,Object> map:result){
			if(PaymentType.Wallet.getType()==SysUtils.Object2int(map.get("pay_type"))){
				statisFlowCharge.setWalletPayAmount(SysUtils.Object2int(map.get("payAmount")));
				statisFlowCharge.setWalletPayCount(SysUtils.Object2int(map.get("payCount")));
			}else if(PaymentType.WebChat.getType()==SysUtils.Object2int(map.get("pay_type"))){
				statisFlowCharge.setQrcodePayAmount(statisFlowCharge.getQrcodePayAmount()+SysUtils.Object2int(map.get("payAmount")));
				statisFlowCharge.setQrcodePayCount(statisFlowCharge.getQrcodePayCount()+SysUtils.Object2int(map.get("payCount")));
				statisFlowCharge.setWeixinPayAmount(SysUtils.Object2int(map.get("payAmount")));
				statisFlowCharge.setWeixinPayCount(SysUtils.Object2int(map.get("payCount")));
			
			}else if(PaymentType.AliPay.getType()==SysUtils.Object2int(map.get("pay_type"))){
				statisFlowCharge.setQrcodePayAmount(statisFlowCharge.getQrcodePayAmount()+SysUtils.Object2int(map.get("payAmount")));
				statisFlowCharge.setQrcodePayCount(statisFlowCharge.getQrcodePayCount()+SysUtils.Object2int(map.get("payCount")));
				statisFlowCharge.setAliPayAmount(SysUtils.Object2int(map.get("payAmount")));
				statisFlowCharge.setAliPayCount(SysUtils.Object2int(map.get("payCount")));
			}else if(PaymentType.NetBankCardQuick.getType()==SysUtils.Object2int(map.get("pay_type"))){
				statisFlowCharge.setBankPayAmount(SysUtils.Object2int(map.get("payAmount")));
				statisFlowCharge.setBankPayCount(SysUtils.Object2int(map.get("payCount")));
			}
		}
		
		if(statisFlowCharge.getId()!=null&&statisFlowCharge.getId()>0){
			statisFlowChargeMapper.updateByPrimaryKey(statisFlowCharge);
		}else{
			statisFlowChargeMapper.insert(statisFlowCharge);
		}
		}
	}

	@Override
	public void saveOilChargeDayStatis(Date statisDate) {
		String statisDateStr=DateUtil.fomatDate(statisDate, DateUtil.sdfDay);
		//
	    List<Long> groupIds=oilcardOrderMapper.findGroupIdInOilchargeOrder(statisDateStr);
	    if(groupIds.size()==0){
	    	groupIds=oilcardRechargeInfoMapper.findGroupIdInOilRechargeInfo(statisDateStr);
	    }
		for(Long groupId:groupIds){
			if(groupId==null){
				continue;
			}
			StatisOilCharge statisOilCharge =statisOilChargeMapper.selectByStatisDate(statisDateStr,groupId);
			if(statisOilCharge==null){
				statisOilCharge=new StatisOilCharge();
				statisOilCharge.setDay(statisDateStr);
				statisOilCharge.setGroupId(groupId);
				statisOilCharge.setGmtCreate(new Date());
				statisOilCharge.setGmtModified(new Date());
				statisOilCharge.setQrcodePayAmount(0);
				statisOilCharge.setQrcodePayCount(0);
				statisOilCharge.setGroupId(groupId);
				statisOilCharge.setWalletPayAmount(0);
				statisOilCharge.setWalletPayCount(0);
			
				statisOilCharge.setWeixinPayAmount(0);
				statisOilCharge.setWeixinPayCount(0);
				statisOilCharge.setAliPayAmount(0);
				statisOilCharge.setAliPayCount(0);
				statisOilCharge.setBankPayAmount(0);
				statisOilCharge.setBankPayCount(0);
			}
			List<Map<String,Object>> result=oilcardOrderMapper.selectStaticGroupByPayType(statisDateStr,groupId);
				
			for(Map<String,Object> map:result){
				if(PaymentType.Wallet.getType()==SysUtils.Object2int(map.get("payment_type"))){
					statisOilCharge.setWalletPayAmount(SysUtils.Object2int(map.get("payAmount")));
					statisOilCharge.setWalletPayCount(SysUtils.Object2int(map.get("rechargeCount")));
				}else if(PaymentType.WebChat.getType()==SysUtils.Object2int(map.get("payment_type"))){
					statisOilCharge.setQrcodePayAmount(statisOilCharge.getQrcodePayAmount()+SysUtils.Object2int(map.get("payAmount")));
					statisOilCharge.setQrcodePayCount(statisOilCharge.getQrcodePayCount()+SysUtils.Object2int(map.get("rechargeCount")));
					statisOilCharge.setWeixinPayAmount(SysUtils.Object2int(map.get("payAmount")));
					statisOilCharge.setWeixinPayCount(SysUtils.Object2int(map.get("rechargeCount")));
				
				}else if(PaymentType.AliPay.getType()==SysUtils.Object2int(map.get("payment_type"))){
					statisOilCharge.setQrcodePayAmount(statisOilCharge.getQrcodePayAmount()+SysUtils.Object2int(map.get("payAmount")));
					statisOilCharge.setQrcodePayCount(statisOilCharge.getQrcodePayCount()+SysUtils.Object2int(map.get("rechargeCount")));
					statisOilCharge.setAliPayAmount(SysUtils.Object2int(map.get("payAmount")));
					statisOilCharge.setAliPayCount(SysUtils.Object2int(map.get("rechargeCount")));
			
				}else if(PaymentType.NetBankCardQuick.getType()==SysUtils.Object2int(map.get("payment_type"))){
					statisOilCharge.setBankPayAmount(SysUtils.Object2int(map.get("payAmount")));
					statisOilCharge.setBankPayCount(SysUtils.Object2int(map.get("rechargeCount")));
				}
			}
			// 统计当日油卡充值金额
			Map<String,Object> rechargeMap=oilcardRechargeInfoMapper.selectStaticByChargeDay(statisDateStr,groupId);
			if(rechargeMap!=null){
				statisOilCharge.setOilChargeAmount(SysUtils.Object2int(rechargeMap.get("rechargeAmount")));
				statisOilCharge.setOilChargeCount(SysUtils.Object2int(rechargeMap.get("rechargeCount")));
			}
			
			if(statisOilCharge.getId()!=null&&statisOilCharge.getId()>0){
				statisOilChargeMapper.updateByPrimaryKey(statisOilCharge);
			}else{
				statisOilChargeMapper.insert(statisOilCharge);
			}
			
		}
		
	}

	@Override
	public OilChargeReportListOutDTO oilChargeReportList(BaseReportInDTO baseReportInDTO) throws Exception {
		OilChargeReportListOutDTO oilChargeReportListOutDTO=new OilChargeReportListOutDTO();
		String startDate=baseReportInDTO.getSelectMonth()+"-01";
		String endDate=baseReportInDTO.getSelectMonth()+"-31";
		Map<String,Object> staticResult=statisOilChargeMapper.selectStaticInfo(startDate,endDate,baseReportInDTO.getGroupId());
		if(staticResult!=null){
			oilChargeReportListOutDTO.setBankPayAmount(SysUtils.Object2Integer(staticResult.get("bankPayAmount")));
			oilChargeReportListOutDTO.setBankPayCount(SysUtils.Object2Integer(staticResult.get("bankPayCount")));
			oilChargeReportListOutDTO.setQrcodePayAmount(SysUtils.Object2Integer(staticResult.get("qrcodePayAmount")));
			oilChargeReportListOutDTO.setQrcodePayCount(SysUtils.Object2Integer(staticResult.get("qrcodePayCount")));
			oilChargeReportListOutDTO.setWalletPayAmount(SysUtils.Object2Integer(staticResult.get("walletPayAmount")));
			oilChargeReportListOutDTO.setWalletPayCount(SysUtils.Object2Integer(staticResult.get("walletPayCount")));
			oilChargeReportListOutDTO.setOilChargeAmount(SysUtils.Object2Integer(staticResult.get("oilChargeAmount")));
			oilChargeReportListOutDTO.setOilChargeCount(SysUtils.Object2Integer(staticResult.get("oilChargeCount")));
			oilChargeReportListOutDTO.setWeixinPayAmount(SysUtils.Object2Integer(staticResult.get("weixinPayAmount")));
			oilChargeReportListOutDTO.setWeixinPayCount(SysUtils.Object2Integer(staticResult.get("weixinPayCount")));
			oilChargeReportListOutDTO.setAliPayAmount(SysUtils.Object2Integer(staticResult.get("aliPayAmount")));
			oilChargeReportListOutDTO.setAliPayCount(SysUtils.Object2Integer(staticResult.get("aliPayCount")));
		
			
			List<StatisOilCharge> resultList= statisOilChargeMapper.selectByGroupIdAndDate(startDate,endDate,baseReportInDTO.getGroupId());;
			oilChargeReportListOutDTO.setStatisOilCharge(resultList);
		}else{
			oilChargeReportListOutDTO.setBankPayAmount(0);
			oilChargeReportListOutDTO.setBankPayCount(0);
			oilChargeReportListOutDTO.setQrcodePayAmount(0);
			oilChargeReportListOutDTO.setQrcodePayCount(0);
			oilChargeReportListOutDTO.setWalletPayAmount(0);
			oilChargeReportListOutDTO.setWalletPayCount(0);
			oilChargeReportListOutDTO.setOilChargeAmount(0);
			oilChargeReportListOutDTO.setOilChargeCount(0);
			oilChargeReportListOutDTO.setWeixinPayAmount(0);
			oilChargeReportListOutDTO.setWeixinPayCount(0);
			oilChargeReportListOutDTO.setAliPayAmount(0);
			oilChargeReportListOutDTO.setAliPayCount(0);
		}
		
		oilChargeReportListOutDTO.setErrorCode(Rescode.SUCCESS, "成功");
		return oilChargeReportListOutDTO;
	}

	@Override
	public OilChargeReportInfoListOutDTO oilChargeReportInfoList(BaseReportInDTO baseReportInDTO) throws Exception {
		OilChargeReportInfoListOutDTO oilChargeReportInfoListOutDTO=new OilChargeReportInfoListOutDTO();
		Map<String,Object> staticResult=null;
		List<OilcardChargeOrderBean> oilcardChargeOrders=null;
		List<OilcardRechargeInfoBean> oilcardRechargeInfos=null;
		if(StringUtils.isNotBlank(baseReportInDTO.getSelectDay())){
			String startDate=baseReportInDTO.getSelectDay();
			String endDate=baseReportInDTO.getSelectDay();
			staticResult=statisOilChargeMapper.selectStaticInfo(startDate,endDate,baseReportInDTO.getGroupId());
			oilcardChargeOrders=oilcardOrderMapper.selectOilChargePaySuccessByGroupId(startDate,endDate,baseReportInDTO.getGroupId());
			oilcardRechargeInfos=oilcardRechargeInfoMapper.selectOilChargeSuccessByGroupId(startDate,endDate,baseReportInDTO.getGroupId());
		}else{
			String startDate=baseReportInDTO.getSelectMonth()+"-01";
			String endDate=baseReportInDTO.getSelectMonth()+"-31";
			staticResult=statisOilChargeMapper.selectStaticInfo(startDate,endDate,baseReportInDTO.getGroupId());
			oilcardChargeOrders=oilcardOrderMapper.selectOilChargePaySuccessByGroupId(startDate,endDate,baseReportInDTO.getGroupId());
			oilcardRechargeInfos=oilcardRechargeInfoMapper.selectOilChargeSuccessByGroupId(startDate,endDate,baseReportInDTO.getGroupId());
		}
		
		oilChargeReportInfoListOutDTO.setOilcardChargeOrders(oilcardChargeOrders);
		oilChargeReportInfoListOutDTO.setOilcardRechargeInfos(oilcardRechargeInfos);
		if(staticResult!=null){
			oilChargeReportInfoListOutDTO.setBankPayAmount(SysUtils.Object2Integer(staticResult.get("bankPayAmount")));
			oilChargeReportInfoListOutDTO.setBankPayCount(SysUtils.Object2Integer(staticResult.get("bankPayCount")));
			oilChargeReportInfoListOutDTO.setQrcodePayAmount(SysUtils.Object2Integer(staticResult.get("qrcodePayAmount")));
			oilChargeReportInfoListOutDTO.setQrcodePayCount(SysUtils.Object2Integer(staticResult.get("qrcodePayCount")));
			oilChargeReportInfoListOutDTO.setWalletPayAmount(SysUtils.Object2Integer(staticResult.get("walletPayAmount")));
			oilChargeReportInfoListOutDTO.setWalletPayCount(SysUtils.Object2Integer(staticResult.get("walletPayCount")));
			oilChargeReportInfoListOutDTO.setOilChargeAmount(SysUtils.Object2Integer(staticResult.get("oilChargeAmount")));
			oilChargeReportInfoListOutDTO.setOilChargeCount(SysUtils.Object2Integer(staticResult.get("oilChargeCount")));
			
			oilChargeReportInfoListOutDTO.setWeixinPayAmount(SysUtils.Object2Integer(staticResult.get("weixinPayAmount")));
			oilChargeReportInfoListOutDTO.setWeixinPayCount(SysUtils.Object2Integer(staticResult.get("weixinPayCount")));
			oilChargeReportInfoListOutDTO.setAliPayAmount(SysUtils.Object2Integer(staticResult.get("aliPayAmount")));
			oilChargeReportInfoListOutDTO.setAliPayCount(SysUtils.Object2Integer(staticResult.get("aliPayCount")));
		
		}else{
			oilChargeReportInfoListOutDTO.setBankPayAmount(0);
			oilChargeReportInfoListOutDTO.setBankPayCount(0);
			oilChargeReportInfoListOutDTO.setQrcodePayAmount(0);
			oilChargeReportInfoListOutDTO.setQrcodePayCount(0);
			oilChargeReportInfoListOutDTO.setWalletPayAmount(0);
			oilChargeReportInfoListOutDTO.setWalletPayCount(0);
			oilChargeReportInfoListOutDTO.setOilChargeAmount(0);
			oilChargeReportInfoListOutDTO.setOilChargeCount(0);
			oilChargeReportInfoListOutDTO.setWeixinPayAmount(0);
			oilChargeReportInfoListOutDTO.setWeixinPayCount(0);
			oilChargeReportInfoListOutDTO.setAliPayAmount(0);
			oilChargeReportInfoListOutDTO.setAliPayCount(0);
		}
		
		oilChargeReportInfoListOutDTO.setErrorCode(Rescode.SUCCESS, "成功");
		return oilChargeReportInfoListOutDTO;
	}

	@Override
	public FlowChargeReportListOutDTO flowChargeReportList(BaseReportInDTO baseReportInDTO) throws Exception {
		FlowChargeReportListOutDTO flowChargeReportListOutDTO=new FlowChargeReportListOutDTO();
		
		String startDate=baseReportInDTO.getSelectMonth()+"-01";
		String endDate=baseReportInDTO.getSelectMonth()+"-31";
		Map<String,Object> staticResult=statisFlowChargeMapper.selectStaticInfo(startDate,endDate,baseReportInDTO.getGroupId());
		if(staticResult!=null){
			flowChargeReportListOutDTO.setBankPayAmount(SysUtils.Object2Integer(staticResult.get("bankPayAmount")));
			flowChargeReportListOutDTO.setBankPayCount(SysUtils.Object2Integer(staticResult.get("bankPayCount")));
			flowChargeReportListOutDTO.setQrcodePayAmount(SysUtils.Object2Integer(staticResult.get("qrcodePayAmount")));
			flowChargeReportListOutDTO.setQrcodePayCount(SysUtils.Object2Integer(staticResult.get("qrcodePayCount")));
			flowChargeReportListOutDTO.setWalletPayAmount(SysUtils.Object2Integer(staticResult.get("walletPayAmount")));
			flowChargeReportListOutDTO.setWalletPayCount(SysUtils.Object2Integer(staticResult.get("walletPayCount")));
			flowChargeReportListOutDTO.setWeixinPayAmount(SysUtils.Object2Integer(staticResult.get("weixinPayAmount")));
			flowChargeReportListOutDTO.setWeixinPayCount(SysUtils.Object2Integer(staticResult.get("weixinPayCount")));
			flowChargeReportListOutDTO.setAliPayAmount(SysUtils.Object2Integer(staticResult.get("aliPayAmount")));
			flowChargeReportListOutDTO.setAliPayCount(SysUtils.Object2Integer(staticResult.get("aliPayCount")));
		}else{
			flowChargeReportListOutDTO.setBankPayAmount(0);
			flowChargeReportListOutDTO.setBankPayCount(0);
			flowChargeReportListOutDTO.setQrcodePayAmount(0);
			flowChargeReportListOutDTO.setQrcodePayCount(0);
			flowChargeReportListOutDTO.setWalletPayAmount(0);
			flowChargeReportListOutDTO.setWalletPayCount(0);
			flowChargeReportListOutDTO.setWeixinPayAmount(0);
			flowChargeReportListOutDTO.setWeixinPayCount(0);
			flowChargeReportListOutDTO.setAliPayAmount(0);
			flowChargeReportListOutDTO.setAliPayCount(0);
		}
		List<StatisFlowCharge> resultList= statisFlowChargeMapper.selectByGroupIdAndDate(startDate,endDate,baseReportInDTO.getGroupId());;
		flowChargeReportListOutDTO.setStatisFlowCharges(resultList);
		flowChargeReportListOutDTO.setErrorCode(Rescode.SUCCESS, "成功");
		return flowChargeReportListOutDTO;
	}

	@Override
	public FlowChargeReportInfoListOutDTO flowChargeReportInfoList(BaseReportInDTO baseReportInDTO) throws Exception {
		FlowChargeReportInfoListOutDTO flowChargeReportInfoListOutDTO=new FlowChargeReportInfoListOutDTO();
		
		Map<String,Object> staticResult=null;
		List<FlowChargeOrderBean> oilcardChargeOrders=null;
		
		if(StringUtils.isNotBlank(baseReportInDTO.getSelectDay())){
			String startDate=baseReportInDTO.getSelectDay();
			String endDate=baseReportInDTO.getSelectDay();
			staticResult=statisFlowChargeMapper.selectStaticInfo(startDate,endDate,baseReportInDTO.getGroupId());
			oilcardChargeOrders=flowChargeMapper.selectOilChargePaySuccessByGroupId(startDate,endDate,baseReportInDTO.getGroupId());
		}else{
			String startDate=baseReportInDTO.getSelectMonth()+"-01";
			String endDate=baseReportInDTO.getSelectMonth()+"-31";
			staticResult=statisFlowChargeMapper.selectStaticInfo(startDate,endDate,baseReportInDTO.getGroupId());
			oilcardChargeOrders=flowChargeMapper.selectOilChargePaySuccessByGroupId(startDate,endDate,baseReportInDTO.getGroupId());
		}
		
		flowChargeReportInfoListOutDTO.setFlowChargeOrders(oilcardChargeOrders);
		if(staticResult!=null){
			flowChargeReportInfoListOutDTO.setBankPayAmount(SysUtils.Object2Integer(staticResult.get("bankPayAmount")));
			flowChargeReportInfoListOutDTO.setBankPayCount(SysUtils.Object2Integer(staticResult.get("bankPayCount")));
			flowChargeReportInfoListOutDTO.setQrcodePayAmount(SysUtils.Object2Integer(staticResult.get("qrcodePayAmount")));
			flowChargeReportInfoListOutDTO.setQrcodePayCount(SysUtils.Object2Integer(staticResult.get("qrcodePayCount")));
			flowChargeReportInfoListOutDTO.setWalletPayAmount(SysUtils.Object2Integer(staticResult.get("walletPayAmount")));
			flowChargeReportInfoListOutDTO.setWalletPayCount(SysUtils.Object2Integer(staticResult.get("walletPayCount")));
			flowChargeReportInfoListOutDTO.setWeixinPayAmount(SysUtils.Object2Integer(staticResult.get("weixinPayAmount")));
			flowChargeReportInfoListOutDTO.setWeixinPayCount(SysUtils.Object2Integer(staticResult.get("weixinPayCount")));
			flowChargeReportInfoListOutDTO.setAliPayAmount(SysUtils.Object2Integer(staticResult.get("aliPayAmount")));
			flowChargeReportInfoListOutDTO.setAliPayCount(SysUtils.Object2Integer(staticResult.get("aliPayCount")));
		}else{
			flowChargeReportInfoListOutDTO.setBankPayAmount(0);
			flowChargeReportInfoListOutDTO.setBankPayCount(0);
			flowChargeReportInfoListOutDTO.setQrcodePayAmount(0);
			flowChargeReportInfoListOutDTO.setQrcodePayCount(0);
			flowChargeReportInfoListOutDTO.setWalletPayAmount(0);
			flowChargeReportInfoListOutDTO.setWalletPayCount(0);
			flowChargeReportInfoListOutDTO.setWeixinPayAmount(0);
			flowChargeReportInfoListOutDTO.setWeixinPayCount(0);
			flowChargeReportInfoListOutDTO.setAliPayAmount(0);
			flowChargeReportInfoListOutDTO.setAliPayCount(0);
		}
		
		flowChargeReportInfoListOutDTO.setErrorCode(Rescode.SUCCESS, "成功");
		return flowChargeReportInfoListOutDTO;
	}
}
